Topic 75 of 83
File I/O
Overview
The standard workflow for File I/O is: Open -> Check if open -> Perform I/O -> Close. Closing is crucial to free up OS file locks and flush buffers.
Syntax
cpp
#include <fstream>
using namespace std;
ofstream file("log.txt");
if (file.is_open()) {
file << "Line 1\n";
file.close(); // Mandatory cleanup
}Common Pitfalls
- Using `cin >> str` or `file >> str` to read a sentence. It stops at the first space. Always use `getline(file, str)` to read full lines.
Interview Tips
- Due to RAII in C++, the destructor of `ofstream`/`ifstream` automatically closes the file when the object goes out of scope. However, calling `.close()` manually is still good practice to catch write errors.
Real-World Example
Reading a file line-by-line.
example
cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("document.txt");
string line;
if (inFile.is_open()) {
// Read until EOF
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Could not open file." << endl;
}
return 0;
}