ifstream::get() surprise

From: Jacek Dziedzic (jacek__NOSPAM___at_janowo.net)
Date: 08/26/04


Date: Thu, 26 Aug 2004 18:21:45 +0200


   Hi!

   Consider the following program

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream in("test.txt");
   char buf[40];
   in.get(buf,40);
   cerr << "Read: *" << buf << "*, trouble: " << !in << endl;
}

and a file, test.txt, starting with an empty line, ie. a lone EOL
character on the first line.

   I was quite surprised to find out, that under these circumstances
the aforementioned program produced
"Read **, trouble: 1".

   Why does 'in' go to a fail state? I thought 'get' reads up to
the terminator, stores all characters into 'buf' and leaves the
terminator inside the stream. That would mean 'buf' containing
just a \0 char (no chars read), the EOL still in the stream, but
why a failed state? There are more lines in the file, so we're
not eof(), and my understanding of this situation is a
"successful read of zero characters" rather than "read error".

   How then can I distinguish a successfull reading of an empty
line from an I/O error during reading a line? Of course I have
no a priori knowledge if these empty lines exist in my parsed
file or not.

TIA,
- J.



Relevant Pages

  • Re: Automatically delete a line if nothing on it??
    ... And Word can't use XML data sources for mailmerges "out of the box". ... The thing is that Word does empty line elimination as standard when it performs a mail merge /and/ the empty line results from a line that has nothing but empty fields, but it doesn't have an automatic facility to eliminate any old empty line, even during a merge. ... characters and then delete that line if no characters are found on it ... Technical Production Assistant ...
    (microsoft.public.word.mailmerge.fields)
  • Re: Pb w/ text i/p to ssh-keygen on openSUSE
    ... for saving the key - but hits a pb after the "Enter passphrase (empty ... even knowing the number of characters compromises security too much. ... Knowing the number of characters is a security hole, indeed, and knowing ...
    (uk.comp.os.linux)
  • Re: Text to Columns
    ... Most likely you have trailing spaces or something (could be invisible html ... characters if you get this info from the web) and the last invisible ... I have already inserted an empty column for the last names. ... Cell A3 has a first and last name. ...
    (microsoft.public.excel.misc)
  • Newbie - need a small push on recursion / higher order procedures
    ... I'm starting out with a string "This is a sentence". ... characters of this string into a list. ... (if (empty? ... (define (create-word sentence) ...
    (comp.lang.scheme)