Skip to content

File Handling in C++

Programming C++ Difficulty 1/5

Beginning of the lesson

File Handling in C++

Save your program's data and read it back later

Big Idea: Normally, everything a program stores in variables disappears the moment it stops. A file lets your program write data onto the disk so it is still there next time the program runs. In C++ we do this with std::ofstream (output — writing) and std::ifstream (input — reading).
By the end you will be able to:
  • include the <fstream> header and open a file,
  • write text and numbers to a file with std::ofstream,
  • read data back with std::ifstream using >> and getline,
  • check that a file opened, close it, and add to it without erasing.

1. Why do we need files?

Think of your program's memory (RAM) like a whiteboard. It is fast and handy while you work, but when the program ends, the whiteboard is wiped clean. A file on the disk is like a notebook: what you write there stays until you change it, even after the computer is turned off.

Files let a game remember your high score, a to-do app keep your tasks, and a program share data with other programs. This ability to keep data after the program closes is called persistence.

2. The fstream toolbox

All file tools live in one header. Add this line at the top of your program:

#include <fstream>

It gives you three stream types. The easy way to remember them is from the point of view of your program:

TypeWhat it doesDirection
std::ofstreamoutput file stream — writes data to a fileprogram → file
std::ifstreaminput file stream — reads data from a filefile → program
std::fstreamcan do both reading and writingboth ways
Notice these behave just like std::cout and std::cin that you already know — you use << to write and >> to read. A file stream is simply cout/cin pointed at a file instead of the screen.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers