01 / 21

File I/O with
fstream

Learn to read from and write to text files using C++ file streams: the gateway to persistent data storage.

C++

What Is File I/O?

File I/O stands for File Input/Output: the process of reading data from files and writing data to files on disk. Without file I/O, every variable you create vanishes when your program ends.

Input
Reading data from a file into your program's variables.
Output
Writing data from your program's variables into a file.

The <fstream> Header

C++ provides file stream classes in the <fstream> header. These classes work just like cin and cout, but connect to files instead of the console.

ifstream
Input file stream: reads data from a file.
ofstream
Output file stream: writes data to a file.
fstream
General file stream: can both read and write.

The Stream Metaphor

Your Program Text File ofstream (write) ifstream (read) Data flows like a stream between your program and the file

Think of a stream as a one-way pipe. An ifstream carries data from the file into your program. An ofstream carries data from your program into the file.

The Core Pattern

Every file operation in C++ follows three steps. This pattern applies whether you are reading or writing.

1
Open the file: create a stream object and connect it to a filename.
2
Read or Write: use operators >>, <<, or getline() to transfer data.
3
Close the file: call .close() to release the file resource.

ifstream vs ofstream vs fstream

ifstream ofstream fstream
Direction Read only Write only Read & Write
Default mode ios::in ios::out None (specify)
Creates file? No Yes Depends on mode
Overwrites? N/A Yes (default) Depends on mode
Best for Loading data Saving data Advanced use

Step-by-Step Checklist

1
#include <fstream> at the top of your file.
2
Declare the stream object: ifstream fin; or ofstream fout;
3
Open the file: fin.open("data.txt"); or use the constructor.
4
Check success: if (!fin) { cerr << "Error"; }
5
Read/Write using >>, <<, or getline().
6
Close the file: fin.close();

Example 1: Writing to a File

#include <iostream> #include <fstream> using namespace std; int main() { ofstream fout("output.txt"); if (!fout) { cerr << "Cannot open file!"; return 1; } fout << "Hello, file!" << endl; fout << "Score: " << 95 << endl; fout.close(); return 0; }

Example 2: Reading from a File

#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream fin("output.txt"); if (!fin) { cerr << "Cannot open file!"; return 1; } string line; while (getline(fin, line)) { cout << line << endl; } fin.close(); return 0; }

Example 3: Reading Word by Word

ifstream fin("data.txt"); string word; while (fin >> word) { cout << "[" << word << "] "; } fin.close();

The extraction operator >> reads one whitespace-delimited token at a time. For a file containing "Hello World 42", this prints:

Appending with ios::app

By default, ofstream overwrites the file. To add to the end without erasing existing content, use the append mode flag.

ofstream fout("log.txt", ios::app); fout << "New log entry" << endl; fout.close();
ios::out (default)
Erases the file and starts fresh. Existing content is lost.
ios::app
Preserves existing content. New data is added at the end.

Reading Numbers from a File

The >> operator automatically converts text to the target variable type. If your file has "3.14 42 100", you can read directly into numeric variables.

ifstream fin("numbers.txt"); double pi; int a, b; fin >> pi >> a >> b; cout << pi << ", " << a << ", " << b; // Output: 3.14, 42, 100 fin.close();

The File I/O Flow

#include <fstream> Declare & Open Stream Check: is_open()? Error! Read / Write Data Close the File 1 2 3 4 5

getline() vs >>

getline(stream, str) stream >> var
Reads Entire line (until newline) One token (until whitespace)
Includes spaces? Yes No
Stores into string only Any compatible type
Stops at '\n' (consumed, not stored) Stops at whitespace, leaves it in stream
Use when Lines have spaces/mixed content Data is space-separated tokens

Common Mistakes

✕ Forgetting to close()
Data may not be flushed to disk. Always call .close() or let the destructor handle it.
✕ Not checking is_open()
If the file doesn't exist, reading silently fails. Always verify the stream before using it.
✕ Mixing >> and getline()
>> leaves '\n' in the buffer. The next getline() reads an empty string. Use fin.ignore() between them.

Summary Reference

Operation Code Notes
Include header #include <fstream> Required for all file I/O
Open for writing ofstream fout("f.txt"); Creates / overwrites
Open for reading ifstream fin("f.txt"); File must exist
Append mode ofstream fout("f.txt", ios::app); Adds to end
Read line getline(fin, str); Includes spaces
Read token fin >> var; Skips whitespace
Write data fout << data << endl; Like cout
Close file fin.close(); Always close

Question 1 of 5

Which header file must you include to use ifstream and ofstream in C++?

Question 2 of 5

What happens by default when you open a file with ofstream and the file already exists?

Question 3 of 5

Which function reads an entire line (including spaces) from a file stream into a string?

Question 4 of 5

What value does name hold after execution?

Question 5 of 5

How do you open a file for writing without erasing its existing content?