Topic 76 of 83
File Modes & EOF
Overview
File modes define how a file is opened (e.g., appending data instead of overwriting, or reading in binary). `.eof()` checks if the end of the file has been reached.
Syntax
cpp
// std::ios::app = Append mode
// std::ios::trunc = Truncate (overwrite, default for ofstream)
// std::ios::binary = Binary mode
ofstream log("log.txt", std::ios::app);
log << "New entry added to the bottom.\n";
// Checking EOF
ifstream in("data.txt");
while (!in.eof()) {
// Process file
}Common Pitfalls
- Using `while(!file.eof())` and unconditionally reading inside the loop. It almost always results in the last line of the file being processed twice.
Interview Tips
- The `eof()` flag is only set AFTER you try to read past the end of the file. Because of this, `while(!file.eof())` often processes the last line twice if written poorly.
Real-World Example
Properly checking for EOF while reading.
example
cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("numbers.txt");
int num;
// The correct way: extraction operator returns true if successful
// This perfectly avoids the duplicate-last-line EOF bug
while (file >> num) {
cout << "Read: " << num << endl;
}
return 0;
}