TITLE: detecting EOF (Newsgroups: comp.lang.c++.moderated, 17 Feb 97) ROWLETT: Aramis@mail.utexas.edu (Brandon Rowlett) >ifstream inputData( "datafile.in"); >if ( inputData.eof() ) > cout << "There is nothing here" ; > >In other words, if the program checks the datafile.in and finds that there >is no information it prints the message out to the screen. Every time I >tried to run it, the compiler skipped over my message, acting as if the >EOF had not been reached. If you create a file and put nothing in it (0 >bytes), is EOF the first item in the file? CLAMAGE: Stephen.Clamage@Eng.Sun.COM (Steve Clamage) The exact time at which eof() becomes true is unspecified. In your example, eof() might be true before you attempt to read, but that requires that the system somehow predict what the unattempted read will produce. In general, you don't want that to be a requirement. For example, if the "file" is the keyboard or a modem, you could not return from constructing or opening the stream until something had been received -- the program could not otherwise predict whether the first thing to be input was an EOF indicator. In addition, reading the last character of a disk file might or might not set EOF. Suppose the size of the file is an exact multiple of the input buffer size. The stream doesn't know if any more characters are available until it attempts to read another buffer. It is possible that particular iostream implementations for particular kinds of devices will display predictive behavior. You can't depend on it in general. ROWLETT: >Is there a way that I can check to see that a file is empty or not? CLAMAGE: Yes. Try to read a character. If it succeeds, the stream is not empty, and you can put the character back. If you somehow know you are dealing with a disk file (as opposed to a keyboard, for example), that will always work. Remember, fstreams, like C stdio FILEs, are specialized for an abstract thing called a "file". That doesn't mean only "disk file", and defined operations have to make sense across a range of devices and platforms. Ordinarily you wouldn't care specifically whether a file was empty (as opposed to containing, say, a single newline and nothing else). It's usually better to write your algorithm to do the right thing when no more data is present. That is, you usually process data with a loop along the lines of while( get_some_data() ) { process_data() } where "get_some_data' is an expression that returns true if more data is available for processing, and false otherwise.