Include <fstream>:
std::ofstream out("file.txt");writes; use<<likecout.std::ifstream in("file.txt");reads; usestd::getline(in, line)or>>.- Files close automatically when the stream object goes out of scope (RAII).
Read and write files with fstream.
✍️ 2 exercises in this lessonInclude <fstream>:
std::ofstream out("file.txt"); writes; use << like cout.std::ifstream in("file.txt"); reads; use std::getline(in, line) or >>.Mastering C++ Files helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
#include <iostream>
#include <fstream>
#include <string>
int main() {
{
std::ofstream out("scores.txt");
out << "Ali 81\nSara 94\nUsman 67\n";
} // file is closed here
std::ifstream in("scores.txt");
std::string name;
int score, best = 0;
std::string bestName;
while (in >> name >> score) {
if (score > best) { best = score; bestName = name; }
}
std::cout << "Top: " << bestName << " (" << best << ")\n";
return 0;
}
Top: Sara (94)
Check what you learned in “C++ Files”.
Open a file for writing.
std:: out("scores.txt");
When is a file stream closed automatically?
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services