Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 23 Beginner

File Handling in C++

Updated: May 17, 2026
5 min read

# CHAPTER 23

File Handling in C++

1. Introduction

When your program ends, all variables in RAM are destroyed. If you want a user's high score or profile data to persist the next time they open the program, you must save it to the hard drive. File Handling allows C++ to read and write permanent files.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Include the <fstream> library.
  • Write to a file using ofstream.
  • Read from a file using ifstream.
  • Append data to an existing file.
  • Check if a file opened successfully.

3. The fstream Library

C++ provides three main classes for working with files:
  • ofstream (Output File Stream): Creates and writes to files.
  • ifstream (Input File Stream): Reads from files.
  • fstream (File Stream): Can do both read and write.

4. Writing to a File (ofstream)

Writing to a file is exactly like using cout, but instead of printing to the console, you print to the file object!
cpp
1234567891011121314151617181920212223
#include <iostream>
#include <fstream> // Required for file handling
using namespace std;

int main() {
    // 1. Create and open a text file
    ofstream outFile("player_stats.txt");

    // 2. Check if it opened successfully
    if (outFile.is_open()) {
        // 3. Write data to the file using <<
        outFile << "Name: Arthur" << endl;
        outFile << "Score: 1500" << endl;
        
        // 4. CLOSE THE FILE!
        outFile.close();
        cout << "Data saved successfully!" << endl;
    } else {
        cout << "Error: Could not create file." << endl;
    }
    
    return 0;
}

5. Appending to a File

By default, ofstream destroys the old file and creates a new one. If you want to *add* data to the end of an existing file, you must open it in Append Mode (ios::app).
cpp
1234
// Open file in append mode
ofstream outFile("player_stats.txt", ios::app); 
outFile << "Level: 5" << endl;
outFile.close();

6. Reading from a File (ifstream)

Reading a file is exactly like using cin. We usually use a while loop combined with getline() to read the file line by line until we reach the End Of File (EOF).
cpp
12345678910111213141516171819202122232425
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string lineText;
    
    // 1. Open the file to read
    ifstream inFile("player_stats.txt");

    if (inFile.is_open()) {
        // 2. Read line by line until EOF
        while (getline(inFile, lineText)) {
            cout << lineText << endl; // Print the line to console
        }
        
        // 3. Close the file
        inFile.close();
    } else {
        cout << "Error: File not found!" << endl;
    }
    
    return 0;
}

7. File Modes

When opening a file, you can specify modes using the bitwise OR operator | to combine them.
  • ios::out : Open for writing (default for ofstream).
  • ios::in : Open for reading (default for ifstream).
  • ios::app : Append to the end of the file.
  • ios::trunc : Truncate (clear) the file before writing (default for out).
  • ios::binary : Open in binary mode (instead of text mode).

8. Mini Project: Notes Manager

cpp
1234567891011121314151617181920212223
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream file("notes.txt", ios::app); // Append mode
    string note;
    
    if (file.is_open()) {
        cout << "Enter a note (or type &#039;EXIT&#039; to quit):" << endl;
        
        while (true) {
            getline(cin, note);
            if (note == "EXIT") break;
            
            file << note << endl; // Save note to file
        }
        file.close();
        cout << "Notes saved!" << endl;
    }
    return 0;
}

9. Memory-Level Explanation

When you open a file, the OS creates a File Descriptor and allocates a buffer in RAM. When you use <<, data goes into the RAM buffer first. It is not written to the hard drive immediately (hard drives are slow). Calling close() forces the buffer to flush (write to disk) and releases the File Descriptor back to the OS.

10. Common Mistakes

  • Forgetting to close() the file: If the program crashes before the file is closed, the buffer might not flush, and your data is lost.
  • Reading a non-existent file: If you don't check isopen(), using ifstream on a missing file will fail silently, leading to confusing bugs.
  • Path Issues: ofstream file("data.txt"); saves the file in the *current working directory*. If you run the executable from a different folder, the file might appear in an unexpected place.

11. Exercises

  1. 1. Write a program that asks the user for their name and age, and writes it to a file called profile.txt.
  1. 2. Write a second program that reads profile.txt and prints the contents to the console.

12. MCQ Quiz with Answers

Question 1

Which library is required for file handling in C++?

Question 2

Which class is used exclusively for writing to files?

Question 3

Which class is used exclusively for reading from files?

Question 4

What is the default behavior of ofstream if the file already exists?

Question 5

Which mode should you use to add data to the end of an existing file?

Question 6

What function reads a file line-by-line?

Question 7

Why is it important to call close() on a file object?

Question 8

Which method checks if a file was successfully found and opened?

Question 9

Which operator is used to write data to an ofstream object?

Q10. Can fstream (without the i or o) be used for both reading and writing? a) Yes b) No Answer: a) Yes

13. Interview Questions

  • Q: Explain the difference between opening a file in Text Mode vs. Binary Mode (ios::binary).
  • Q: What is Serialization?
  • Q: Explain what a Buffer is in the context of file I/O and why it is used.

14. Summary

File handling allows your data to outlive the program's execution. By treating files as streams (using << to write and getline to read), C++ makes saving to the hard drive as easy as printing to the console. Always remember to check is_open() and to close() your files!

15. Next Chapter Recommendation

In Chapter 24: Multithreading in C++, we will learn how to make our programs do two things at exactly the same time by utilizing multiple CPU cores.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·