Handling end-of-file (eof) correctly

The eof() function, as in   infile.eof()  , is a bool function which is true if the EOF character has been read, false otherwise. When you have read the last item in a file, the eof function may not be true yet. Often you have to read past the last item in the file to read the EOF character so the eof function will be true.

On unix, every line in a file has an End-Of-Line (EOL) character and the EOF character is after the last line. On windows, each line has an EOL characters except the last line. There is an EOF character after the last line. So unix file's last line is
      stuff, EOL, EOF
whereas windows file's last line, if the cursor is on the line, is
      stuff, EOF

So if you always read past the last item, meaning you try to read an item that is not there, you will correctly determine eof under both unix and windows. In general, you must exit all loops and all functions immediately when you are attempting to read an item that would be past the eof.

Here is a typical set up that will work correctly. Adapt appropriately to your situation. In a file is multiple sets of data for one item. In some function is the loop where you are reading and handling these sets of data. This loop will look similar to the following.
     // infinite loop to read and handle a line of data
     for (;;) {
        // do any initializing
        infile >> firstThingOnTheLine;
        if (infile.eof()) break;

        // read the rest of the line
        // do whatever with data
     }
Often reading is done in a routine. In that case, exit both. This loop is similar to that situation.
        for (;;) {
           // do any initializing
           obj.setdata(infile);      // method finishes reading
           if (infile.eof()) break;

           // do whatever with obj
        }

     void objClass::setdata(istream& infile) {
          infile >> firstThingOnTheLine;   // so EOF char is read
          if (infile.eof()) return;        // determine no more data

          // probably read more data to fill rest of object
     }