Until now, our programs have mostly worked with data while the program is running. But what if you want to save information and use it later?
For example, you may want to save:
- Student names
- Marks
- Notes
- Game scores
C++ provides file handling to create, write, read, and manage files. Let’s begin with understanding C++ File Handling.
What is File Handling in C++?
File handling means using a C++ program to create, open, write, read, and close files. C++ provides three important classes for file handling:
ofstream→ Used mainly for writingifstream→ Used mainly for readingfstream→ Used for both reading and writing
To use them, include:
#include <fstream>
Creating and Opening a File
Let’s create a file called student.txt.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("student.txt");
if (file.is_open()) {
cout << "File created and opened successfully.";
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
File created and opened successfully.
If student.txt does not already exist, C++ will create it.
If the file already exists, opening it with ofstream can replace its existing content when we write new data.
Writing to a File
We can use ofstream to write information into a file.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("student.txt");
if (file.is_open()) {
file << "Name: Rahul\n";
file << "Age: 14\n";
file << "Marks: 90\n";
file.close();
cout << "Data written successfully.";
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
Data written successfully.
Now open student.txt on your computer.
It will contain:
Name: Rahul
Age: 14
Marks: 90
This line:
file << "Name: Rahul\n";
writes the text into the file. The \n moves the next text to a new line.
Reading From a File
We can use ifstream to read information from a file. First, make sure student.txt contains:
Rahul
14
90
Now let’s read it using C++:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("student.txt");
if (file.is_open()) {
string name;
int age;
int marks;
file >> name;
file >> age;
file >> marks;
cout << "Name: " << name << "\n";
cout << "Age: " << age << "\n";
cout << "Marks: " << marks;
file.close();
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
Name: Rahul
Age: 14
Marks: 90
Here:
file >> name;
reads the first value from the file.
Then:
file >> age;
reads the next value.
And:
file >> marks;
reads the next value.
Reading a Complete Line
The >> operator reads one word at a time. If the file contains a name with spaces, such as:
Rahul Sharma
we can use getline() to read the complete line.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("student.txt");
if (file.is_open()) {
string name;
getline(file, name);
cout << "Name: " << name;
file.close();
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
Name: Rahul Sharma
getline() reads the complete line, including spaces.
Closing a File
After finishing our work with a file, we should close it.
We use:
file.close();
For example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("message.txt");
if (file.is_open()) {
file << "Hello from C++.";
file.close();
cout << "File closed successfully.";
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
File closed successfully.
Closing the file tells C++ that we have finished working with it.
ofstream in C++
ofstream is mainly used to write data to a file.
Here is a complete example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("data.txt");
if (file.is_open()) {
file << "Welcome to C++ File Handling!\n";
file << "This information is saved in a file.";
file.close();
cout << "Data saved successfully.";
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
Data saved successfully.
Remember:
ofstream → Write to a file
ifstream in C++
ifstream is mainly used to read data from a file. Suppose data.txt contains:
Welcome to C++!
We can read it using:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("data.txt");
if (file.is_open()) {
string text;
getline(file, text);
cout << "File contains: " << text;
file.close();
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
File contains: Welcome to C++!
Remember:
ifstream → Read from a file
fstream in C++
fstream can be used for both reading and writing. Let’s create a complete example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("data.txt", ios::in | ios::out | ios::trunc);
if (file.is_open()) {
file << "Hello C++";
file.seekg(0);
string text;
getline(file, text);
cout << "File contains: " << text;
file.close();
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
File contains: Hello C++
Here:
ios::in
allows reading.
ios::out
allows writing.
The ios::trunc option clears the old content when the file is opened.
The line:
file.seekg(0);
moves the reading position back to the beginning of the file. Remember:
fstream → Read + Write
A Complete C++ File Handling Example
Let’s create a small program that saves student information and then reads it.
Step 1: Write the Information
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("student.txt");
if (file.is_open()) {
file << "Rahul Sharma\n";
file << "14\n";
file << "90\n";
file.close();
cout << "Student information saved successfully.";
} else {
cout << "Unable to open the file.";
}
return 0;
}
After running the program, student.txt will contain:
Rahul Sharma
14
90
Step 2: Read the Information
Now we can use another program to read the saved information:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("student.txt");
if (file.is_open()) {
string name;
int age;
int marks;
getline(file, name);
file >> age;
file >> marks;
cout << "Student Information\n";
cout << "Name: " << name << "\n";
cout << "Age: " << age << "\n";
cout << "Marks: " << marks << "\n";
file.close();
} else {
cout << "Unable to open the file.";
}
return 0;
}
Output:
Student Information
Name: Rahul Sharma
Age: 14
Marks: 90
This is the basic idea of file handling: one program can save information, and another program can read it later.
Key Points to Remember
- File handling allows C++ programs to work with files.
ofstreamis mainly used for writing.ifstreamis mainly used for reading.fstreamcan be used for both reading and writing.file <<writes data into a file.file >>reads data from a file.getline()reads a complete line.file.close()closes a file.- Always check whether a file opened successfully before using it.
Mini Quiz
Mini Project
Mini Project: Personal Diary
Question:
Write a C++ program that allows a user to save a diary entry and read it from a file.
- Take a diary entry using
getline(). - Save the entry in a file named
diary.txt. - Use
ofstreamto write the entry. - Close the file after saving.
- Open the same file using
ifstream. - Read the complete entry using
getline(). - Display the saved diary entry.
- Display a suitable message if the file cannot be opened.
View Answer Code
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string entry;
cout << "Write your diary entry: ";
getline(cin, entry);
ofstream file("diary.txt");
if (file.is_open()) {
file << entry;
file.close();
cout << "\nDiary entry saved successfully.\n";
}
else {
cout << "Unable to open the file.";
return 0;
}
ifstream readFile("diary.txt");
if (readFile.is_open()) {
string savedEntry;
getline(readFile, savedEntry);
cout << "\nYour Diary Entry:\n";
cout << savedEntry;
readFile.close();
}
else {
cout << "Unable to open the file.";
}
return 0;
}
What’s Next?
In the next chapter, we will learn about C++ STL (Standard Template Library) and explore useful tools
Frequently Asked Questions (FAQs)
Q1. What is C++ File Handling?
C++ File Handling allows programs to create, open, read, write, and close files using classes such as ofstream, ifstream, and fstream.
Q2. How do you read and write files in C++?
Use ofstream to write data to a file and ifstream to read data from a file.
Q3. What is ofstream in C++ used for?
ofstream is mainly used to create files and write data into them.
Q4. What is ifstream in C++ used for?
ifstream is used to open and read data from an existing file.
Q5. What is the difference between ofstream and ifstream?
ofstream is mainly used for file output and writing, while ifstream is mainly used for file input and reading.
Q6. Why is File Handling in C++ useful for storing data?
File Handling in C++ lets a program store information permanently in files, so the data can be accessed again even after the program has ended.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
