C++ Files

Read and write files with fstream.

✍️ 2 exercises in this lesson

Include <fstream>:

  • std::ofstream out("file.txt"); writes; use << like cout.
  • std::ifstream in("file.txt"); reads; use std::getline(in, line) or >>.
  • Files close automatically when the stream object goes out of scope (RAII).

Key Takeaways: C++ Files

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.

C++ Files Code Example

C++
#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;
}
Output
Top: Sara (94)
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Files Practice Exercises

Check what you learned in “C++ Files”.

/ 2 solved
Fill in the blank

Open a file for writing.

std:: out("scores.txt");
✓ Correct! Not quite. Try again.
Multiple choice

When is a file stream closed automatically?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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