File Handling in C++: Reading, Writing, Opening, and Closing Files
What is File Handling in C++: Reading, Writing, Opening, and Closing Files? File handling in C++ is performed using stream classes from ``: `std::ifstream` for reading, `std::ofstream` for writing, and `std::fstream` for combined read/w...
How does file I/O work in C++ using std::ifstream, std::ofstream, and std::fstream in <fstream>?
Explanation & In-Depth Details
```text
┌──────────────────┐
│ std::ios │
└────────┬─────────┘
│
┌────────────────┴────────────────┐
│ │
┌───────┴────────┐ ┌───────┴────────┐
│ std::istream │ │ std::ostream │
└───────┬────────┘ └───────┬────────┘
│ │
┌───────┴────────┐ ┌───────┴────────┐
│ std::ifstream │ │ std::ofstream │
└────────────────┘ └────────────────┘
```
2. Open Modes:
- `std::ios::in`: Read mode.
- `std::ios::out`: Write mode (truncates file by default).
- `std::ios::app`: Append mode.
- `std::ios::binary`: Binary mode without newline translation.
Code Example
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main() {
// 1. Writing to a file (RAII closes stream automatically)
{
std::ofstream outFile("server_config.txt");
if (outFile.is_open()) {
outFile << "PORT=8080\n";
outFile << "HOST=127.0.0.1\n";
outFile << "WORKERS=8\n";
std::cout << "Configuration written successfully.\n";
}
} // File closed here
// 2. Reading line by line
std::ifstream inFile("server_config.txt");
if (inFile.is_open()) {
std::string line;
std::cout << "\nReading Configuration File:\n";
while (std::getline(inFile, line)) {
std::cout << " > " << line << "\n";
}
} else {
std::cerr << "Failed to open file for reading.\n";
}
return 0;
}Interview Question & Tips
A: No, file stream destructors automatically flush buffers and close the open file handle when the stream object goes out of scope (RAII), though explicit `.close()` is useful if you need to check for write-flush errors immediately.
Q: How do you read an entire file into a `std::string` efficiently?
A: Using stringstream: `std::stringstream buffer; buffer << file.rdbuf(); std::string content = buffer.str();`
Best Practices
• Use `std::getline(file, line)` to safely read files line by line without buffer overflow risks.
• Open files with `std::ios::binary` when reading or writing non-text binary formats.
This study reference for File Handling in C++: Reading, Writing, Opening, and Closing Files is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: