Home >Backend Development >C++ >How to Correctly Test for End-of-File When Reading from a File Stream in C ?
Testing Stream Input State vs. Future Success
When reading input using streams, it's essential to understand the difference between testing stream state and predicting the success of future operations.
Issue: Reading Last Line Twice
ifstream f("x.txt"); string line; while (f.good()) { getline(f, line); // Use line here. }
In this code, the last line is read twice because f.good() tests the current stream state, not whether getline() will succeed. Once getline() reaches the EOF, f remains in a "good" state, so the loop continues even after the last line has been read.
Solution: Test Stream After Operation
Instead, check the stream state after performing the input operation:
ifstream f("x.txt"); string line; while (getline(f, line)) { // Use line here. }
Alternative Using eof()
While it's not recommended to use eof() in loop conditions, here's an equivalent solution using !f.eof():
ifstream f("x.txt"); string line; while (!f.eof()) { if (getline(f, line)) { // Use line here. } else { break; } }
Range-Based Loop for All Lines
To read and process all lines, use a range-based loop:
ifstream f("x.txt"); for (std::string line; getline(f, line);) { process(line); }
Good vs. Stream State
Note that f.good() is misnamed. It does not truly indicate the stream's "goodness" but rather returns true when the stream is not in a "fail" or "bad" state. Always test the stream itself (i.e., check its inverted fail state) after performing input operations to ensure success.
The above is the detailed content of How to Correctly Test for End-of-File When Reading from a File Stream in C ?. For more information, please follow other related articles on the PHP Chinese website!