EOF not found

Hello,

I"m using the following c++ program on a Linux Redhat System, where it works fine.
But as soon as I move on a SunOS there will be no end of reading?

#include <fstream> 
#include <iostream>

ifstream     file("test"); 
string         buffer; 
int         i=0; 
      
 if (file.is_open()) { 
   while (!file.eof())  
   { 
     cout <<  "EOF: " << file.eof() << endl; 
          
         i++; 
        try {
         getline(file, buffer);        
          cout << i << ": "<< buffer << endl; 
         }  catch (exception& ex) { 
         cout << "ERROR READING!" <<endl;  
     }   
   } 
   file.close(); 
 }

I really don't know what to do and where it comes from?
Has anyone an idea?

Thanks Tim

What exactly does it do on fedora? Does it output "ERROR READING!" on fedora or not?

I can see two possible ways this program could operate depending on how its iostream works underneath. If iostream can detect EOF before a read actually fails, then it will break the while loop before any message is printed. But if it can't detect EOF until a read actually fails, then it will throw the exception and print "ERROR READING!". I'm not positive but I believe both behaviors are valid ways for iostream to work, particularly since it's hard to detect EOF on things like sockets and pipes until a read actually fails.

A big thank you for your reply - I'm really stuck.
So there is no error message at all:
if there a 5 lines in a textfile for example, it keeps printing out:

6: 
7:
8:
...

and so on. So the buffer is empty, but no exception is thrown, but if I put getline(file, buffer); in the while loop, like this:

while (getline(file, buffer))  
  • it will return false, thus it ends when there are no more lines available.

But nevertheless I don't know why EOF fails. The same happens with file.good(). Somehow they never return false;

I now see that getline returns a value, which may be why it doesn't throw an exception on all systems -- it can't do both at the same time, the implementor had to pick one in the event of failure. As for why EOF doesn't occur after a failed getline, I can only guess how Sun implemented their iostream. It certainly looks like it ought to produce EOF under those circumstances. So I guess you'll just need to check all return values for errors to be compatible with both. Which is probably a good idea anyway...

so your usual while loop, and with the getline, you do this:

try{
if(getline(file, buffer) <= 0)
  break;
}

which will cause the loop to break when getline fails as well as checking for exceptions.