C++ › I/O Streams

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

Intermediate

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.

Common follow-ups: How do you check a file opened? | Which stream closes the file?