Topic 74 of 83
File Streams
Overview
File I/O allows your program to persist data to the hard drive. C++ uses the `<fstream>` library, providing `ifstream` (Input File Stream, for reading) and `ofstream` (Output File Stream, for writing).
Syntax
cpp
#include <fstream>
// Writing
std::ofstream out("data.txt");
out << "Saving this to disk!";
out.close();
// Reading
std::ifstream in("data.txt");
std::string text;
in >> text;
in.close();Common Pitfalls
- Assuming a file opened successfully. Always check `if (file.is_open())` before trying to read or write.
Interview Tips
- Explain that `cout` and `cin` are just streams linked to the console. `ofstream` and `ifstream` work exactly the same way, but are linked to files instead.
Real-World Example
The `<fstream>` hierarchy.
example
cpp
/*
ios_base
|
ios
/ \
istream ostream
| |
ifstream ofstream
fstream inherits from both istream and ostream, allowing read/write on the same file.
*/