C++ File Handling
The `<fstream>` header provides `ifstream` (input/reading), `ofstream` (output/writing), and `fstream` (both) for working with files. You open a file, perform reads/writes, then close it (or let the destructor close it automatically).
Always check whether a file opened successfully before using it, since a missing or locked file will cause the stream to enter a failed state silently.
Writing to a file
`std::ofstream out("data.txt"); out << "Hello"; out.close();` creates/overwrites data.txt with the given text.
Reading from a file
`std::ifstream in("data.txt"); std::string line; while (getline(in, line)) { ... }` reads the file line by line until the end.
#include <fstream>
int main() {
std::ofstream out("data.txt");
out << "Hello, File!";
out.close();
}(creates data.txt containing 'Hello, File!')ofstream writes text into a new or existing file.
std::ifstream in("data.txt");
std::string line;
getline(in, line);
std::cout << line;Hello, File!ifstream reads the file's content back into a string.
Key points
- <fstream> provides ifstream, ofstream, and fstream.
- Always check if(file) or file.is_open() before use.
- close() releases the file, though destructors do this too.
- getline() reads a file line by line.
