-
Hajipur, Bihar, 844101
In most real-world programs, we need to store information permanently so that it remains available even after the program ends. This is where file handling becomes useful. In C++, files allow you to save, read, and modify data stored on your computer’s hard drive instead of using temporary memory.
C++ provides a simple way to work with files using the <fstream> library, which includes special classes for reading and writing data efficiently.
The <fstream> header file in C++ provides three main classes for handling files:
ofstream – Used to create and write data to files.
ifstream – Used to read data from files.
fstream – Used for both reading and writing files.
These classes behave like input and output streams (such as cin and cout) but work with files instead of the console.
To use file handling features in your program, include the following header files:
#include <iostream>
#include <fstream>
using namespace std;
Before reading or writing data, you must open the file. When the operation is done, close the file to free system resources.
Example:
ofstream file("example.txt"); // open file for writing
ifstream file("example.txt"); // open file for reading
file.close(); // close the file
Always make sure to close files after use to avoid memory leaks or corruption.
The ofstream class is used to write data to a file.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("data.txt"); // open file in write mode
if (file.is_open()) {
file << "Welcome to C++ File Handling.\n";
file << "This line will be written inside the file.\n";
file.close();
cout << "Data written successfully.\n";
} else {
cout << "Unable to open file.";
}
return 0;
}
If the file doesn’t exist, C++ automatically creates one.
To read content from a file, use the ifstream class.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("data.txt"); // open file in read mode
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << "Unable to open file.";
}
return 0;
}
This reads and displays each line of the file using getline().
If you want to add new content without deleting old data, open the file in append mode using ios::app.
Example:
ofstream file("data.txt", ios::app);
file << "This is a new line added at the end.\n";
file.close();
Here, the ios::app flag adds new text to the end of the existing file instead of overwriting it.
C++ supports several file opening modes that define how a file should be used. You can also combine them using the OR (|) operator.
| Mode | Description |
|---|---|
| ios::in | Opens file for reading |
| ios::out | Opens file for writing |
| ios::app | Opens file in append mode |
| ios::trunc | Deletes old content if the file exists |
| ios::binary | Opens file in binary mode |
Example:
fstream file;
file.open("data.txt", ios::out | ios::app);
file << "Data added using fstream.\n";
file.close();
Text files are easy to read but not efficient for storing structured data. Binary files are faster and more compact because they store data in binary form.
Example:
#include <iostream>
#include <fstream>
using namespace std;
class Student {
public:
char name[30];
int age;
};
int main() {
Student s1 = {"Anita", 20};
ofstream file("student.bin", ios::binary);
file.write((char*)&s1, sizeof(s1));
file.close();
Student s2;
ifstream infile("student.bin", ios::binary);
infile.read((char*)&s2, sizeof(s2));
infile.close();
cout << "Name: " << s2.name << ", Age: " << s2.age;
return 0;
}
This program stores a class object into a binary file and reads it back later.
You can check whether a file exists before reading or writing:
ifstream file("data.txt");
if (file) {
cout << "File exists.\n";
} else {
cout << "File not found.\n";
}
file.close();
Here are some common mistakes programmers make when handling files:
Forgetting to close the file after using it.
Opening a file in the wrong mode (for example, trying to read a write-only file).
Not checking whether the file opened successfully.
Using incorrect file paths or missing extensions.
File handling in C++ allows you to permanently store and retrieve data. You can create, read, write, or append text and binary files using the ofstream, ifstream, and fstream classes. Always open files with the correct mode and close them after use. Understanding file handling is essential for building applications that require data persistence, such as databases, logs, or configuration systems.
Write a C++ program to create a text file named info.txt and store your name, age, and city in it using ofstream.
Create a C++ program that reads and displays the contents of a file named info.txt using ifstream.
Write a program to append a new line of text to an existing file without deleting its old content.
Create a program that takes input from the user and writes it into a file called notes.txt.
Write a C++ program that counts the number of lines in a given file and displays the count on the screen.
Create a class Student that stores a student’s name and marks. Write an object of this class to a binary file and then read it back.
Write a C++ program that reads a file character by character and displays it on the screen.
Write a program to copy the contents of one text file (source.txt) to another file (target.txt).
Develop a program that checks if a file exists before trying to open it, and displays a message accordingly.
Create a program that writes multiple lines of user input to a file until the user enters “exit”.