Back to C++
2026-03-025 min read

C++ <fstream>

Learn C++ <fstream> step by step with clear examples and exercises.

Title: Mastering C++ File Streams with Library

Why This Matters

In this lesson, we delve into the world of file handling in C++ using the powerful library. Understanding and mastering file streams is crucial for real-world applications like data persistence, logging, and system administration. It can also help you ace job interviews, as many employers look for candidates with strong file I/O skills.

Prerequisites

To follow this lesson, you should have a good understanding of the following:

  1. Basic C++ syntax (variables, functions, loops, and control structures)
  2. Standard input/output (std::cin, std::cout)
  3. Object-oriented programming concepts in C++
  4. Understanding of basic file systems

Core Concept

The library provides a set of classes for performing various types of file operations, such as reading from and writing to files. It includes the following classes:

  1. std::ifstream - input file stream (for reading)
  2. std::ofstream - output file stream (for writing)
  3. std::fstream - file stream (for both reading and writing)

Each of these classes derives from the basic stream class std::istream, std::ostream, or both, depending on their functionality.

Opening a File

To open a file for reading or writing, you need to create an instance of the appropriate stream class and call the open() function. For example:

#include <iostream>
#include <fstream>

int main() {
std::ifstream inputFile("example.txt"); // Open a file for reading
std::ofstream outputFile("output.txt"); // Open a file for writing

if (!inputFile) {
std::cout << "Unable to open example.txt\n";
return 1;
}

if (!outputFile) {
std::cout << "Unable to create output.txt\n";
return 1;
}
}

In this example, we're opening two files: example.txt for reading and output.txt for writing. If the files cannot be opened or created, the program will print an error message and exit.

Reading from a File

To read data from a file, you can use the member functions provided by the stream classes. For example:

std::string line;
while (getline(inputFile, line)) {
std::cout << "Line read: " << line << '\n';
}

In this code snippet, we're reading lines from the example.txt file until the end of the file and printing each line to the console.

Writing to a File

To write data to a file, you can use the << operator:

outputFile << "Hello, World!\n"; // Write a string to output.txt

You can also write variables and expressions to the file using the same approach:

int number = 42;
outputFile << number << '\n'; // Write an integer to output.txt

Closing a File

Always remember to close the file when you're done with it, as this frees up system resources:

inputFile.close();
outputFile.close();

Worked Example

In this example, we'll create a simple program that reads numbers from example.txt, calculates their sum, and writes the result to output.txt.

  1. Create an example.txt file with some integers:
1
2
3
4
5
  1. Write the C++ code:
#include <iostream>
#include <fstream>

int main() {
std::ifstream inputFile("example.txt");
std::ofstream outputFile("output.txt");

if (!inputFile) {
std::cout << "Unable to open example.txt\n";
return 1;
}

if (!outputFile) {
std::cout << "Unable to create output.txt\n";
return 1;
}

int sum = 0;
int number;

while (inputFile >> number) {
sum += number;
}

outputFile << "Sum: " << sum << '\n';

inputFile.close();
outputFile.close();

return 0;
}
  1. Compile and run the program:
g++ example.cpp -o example
./example
  1. Check the result in output.txt:
Sum: 15

Common Mistakes

  1. Forgetting to include the library:
#include <iostream> // Incorrect!

Instead, you should include both ` and `:

#include <iostream>
#include <fstream> // Correct!
  1. Failing to check if the file can be opened or created:
std::ifstream inputFile("example.txt");
std::ofstream outputFile("output.txt");

In this case, the program will crash if example.txt does not exist or is not readable. Always check for errors and handle them gracefully:

if (!inputFile) {
std::cout << "Unable to open example.txt\n";
return 1;
}

if (!outputFile) {
std::cout << "Unable to create output.txt\n";
return 1;
}
  1. Not closing the file after use:
std::ifstream inputFile("example.txt");
std::ofstream outputFile("output.txt");
// ... (read and write operations)

Always close the files when you're done with them to free up system resources:

inputFile.close();
outputFile.close();

Practice Questions

  1. Write a program that reads lines from example.txt and writes them in reverse order to output.txt.
  2. Modify the example program to calculate the average of the numbers in example.txt instead of their sum.
  3. Create a program that reads two integers from the console, writes them to numbers.txt, and then reads the numbers back from the file and prints their product.

FAQ

--

Q: Why do I get an error when trying to open a file in my C++ program?

A: Make sure that the file exists and has the correct permissions, and check if you've included the library in your code.

Q: How can I read binary files using C++ and the library?

A: To read binary files, use the std::ifstream class with the binary mode flag (ios::binary) set:

std::ifstream inputFile("example.bin", std::ios::binary);

Q: How can I write to a file in append mode using C++ and the library?

A: To write to a file in append mode, use the std::ofstream class with the append mode flag (ios::app) set:

std::ofstream outputFile("output.txt", std::ios::app);

With this complete lesson on C++ file streams using the library, you're well-equipped to tackle various I/O tasks in your programs and stand out during job interviews!

C++ &lt;fstream&gt; | C++ | XQA Learn