Advertisement
Intermediate C++, I/O Streams

How do you read a file with ifstream and write with ofstream?

Short answer

std::ifstream opens a file for reading and std::ofstream for writing; std::fstream does both. They're RAII—opening in the constructor and closing in the destructor—and use the same > and getline as other streams. Always check that the stream opened successfully before using it.

Save C++ mock interview
Advertisement
AModel answer
std::ifstream opens a file for reading and std::ofstream for writing; std::fstream does both. They're RAII—opening in the constructor and closing in the destructor—and use the same << / >> and getline as other streams. Always check that the stream opened successfully before using it.
std::ifstream in("data.txt");
if (!in) { /* handle error */ }
std::string line;
while (std::getline(in, line)) { /* process */ }
Real-world example
A config loader reads lines from an ifstream, which closes automatically via RAII when it goes out of scope.
Likely follow-ups
  • How do you check a file opened? | Which stream closes the file?
Related topics