Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔵 Core C++  ·  Lesson 36

File Handling in C++

In this lesson: Read and write files in C++ with ifstream, ofstream and fstream — modes and examples with output. In Hindi & English.

File handling in C++

File handling lets a program save data to disk and read it back. C++ uses the <fstream> library with three classes: ofstream (write), ifstream (read), and fstream (both). They work just like cout and cin, but on files.

Writing to a file

C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream out("data.txt");        // open for writing
    out << "Hello file\n";
    out << "Second line\n";
    out.close();                     // close when done
    cout << "Written.\n";
    return 0;
}
Output:
Written.
(data.txt now contains the two lines)

Reading from a file

C++
ifstream in("data.txt");         // open for reading
string word;
while (in >> word) {              // read word by word
    cout << word << " ";
}
in.close();

Reading line by line

Use getline to read whole lines, which keeps spaces:

C++
ifstream in("data.txt");
string line;
while (getline(in, line)) {
    cout << line << "\n";
}
in.close();

File open modes

ModeMeaning
ios::inOpen for reading
ios::outOpen for writing (clears file)
ios::appAppend to the end
ios::truncTruncate existing content
ios::binaryBinary mode
C++
ofstream out("log.txt", ios::app);   // add without erasing

Checking for errors

Always confirm the file opened before using it:

C++
ifstream in("missing.txt");
if (!in) {                        // or in.is_open()
    cout << "Could not open file\n";
    return 1;
}

Common mistakes

  • Not checking whether the file opened before reading/writing.
  • Forgetting to close() (or relying on scope to close it).
  • Using ios::out when you meant ios::app, wiping the file.
  • Mixing >> (stops at spaces) with getline without clearing the newline.
🏋️ Practice

Write a program that appends a new line to notes.txt each run, then reads the whole file back and prints it with line numbers. Handle the case where the file does not yet exist.

Summary

  • File handling uses <fstream>: ofstream, ifstream, fstream.
  • Write with <<, read with >> or getline.
  • Open modes like ios::app and ios::binary control behaviour.
  • Always check the file opened before using it.
  • Close files when finished.

Frequently Asked Questions

How do you handle files in C++?
C++ handles files with the <fstream> library, which provides three stream classes: ofstream for writing, ifstream for reading, and fstream for both. You open a file through one of these objects, use stream operators to read or write, and close it when done.
What is the difference between ifstream, ofstream, and fstream in C++?
ifstream is an input file stream used only for reading, ofstream is an output file stream used only for writing, and fstream can do both reading and writing on the same file. You choose based on whether you need to read, write, or both.
How do you read a file line by line in C++?
You open the file with an ifstream and call getline(file, line) inside a loop, which reads one line at a time into a string until the end of the file. This is the standard way to process a text file line by line.
What are file open modes in C++?
Open modes control how a file is opened, such as ios::in for reading, ios::out for writing, ios::app to append, ios::trunc to clear existing content, and ios::binary for binary data. You can combine them with the bitwise OR operator when opening a file.
How do you check if a file opened successfully in C++?
After opening, you test the stream, for example with if (!file) or if (!file.is_open()). If the check fails the file could not be opened — perhaps it does not exist or there is no permission — and you should handle that before reading or writing.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicObject-Oriented Programming Concepts Your progress: 36 / 81 (44%) · Lesson 37 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free