Subj : Re: EOF (end of file) problem To : borland.public.cpp.borlandcpp From : maeder@glue.ch (Thomas Maeder [TeamB]) Date : Sat Nov 01 2003 01:12 pm Karlo Basic writes: > I hope I'm asking the right question in the right group. Strictly speaking, you don't. But I refrain from my usual response this time, because your question is relevant to Borland C++ (to whom this newsgroup is on topic) users as well to C++ Builder users like you. > I have a problem with a piece of C++ code that runs well under Linux > (gcc 2.96) but doesn't run as expected in Windows (Borland C++ 5.5.1): Borland C++ 5.5.1 is what the C++ Builder 5 command line compiler calls itself, somewhat misleadingly IMHO. BTW: There was never a gcc 2.96; the latest 2.xx releases all had 2.95.x. 2.96 is just a RedHat hack. > Here's the code: > ********** > int num; > ifstream in_file; > in_file.open("whatever.txt"); > while (!in_file.eof()) > cin >> num; > ********** This code is not correct. First of all, I believe you mean the last line to read in_file >> num; , or you'll have an infinite loop. Please take care to always copy&paste minimal code as you have tested it; don't re-type. Second, the only way the while loop can stop is when the eof flag inside in_file is set. Now input from in_file can fail for other reasons than end of file; once this happens, you'll have an infinite loop, as well, because the flags inside in_file aren't going to change any more. A correct version of your program looks like this: #include #include int main() { std::ifstream in_file("whatever.text"); int num; while (in_file >> num) std::cout << num << '\n'; } [I've added the output line to make testing easier] Note to Borland C++ users: In Borland C++, and might have to be #included, and the std:: qualifications removed. The big differences between our programs are: - mine checks for failure only after the read attempt; stream flags such as end of file and input failure are only set while reading, never before reading - the loop stops after any kind of input failure has been met: file can't be opened, bad input, end of file, you name it > Example input: > 1 2 3 4 5 6 7EOF -> Linux OK; Windows not > 1 2 3 4 5 6 7 > EOF -> Linux & Windows OK I think that this difference should go away in my program. .