File handling in C++ allows a program to create, open, read,
write, append, and manage data stored in files. C++ provides file
stream classes such as std::ifstream,
std::ofstream, and std::fstream for working
with files.
File handling means working with files to store and retrieve data.
A C++ program can perform operations such as:
File handling allows information to remain available even after the program ends.
Variables store data temporarily while a program is running. Files allow data to be stored for later use.
For example, a student management program can store:
The stored information can be read again when the program runs later.
C++ provides file stream classes in the <fstream>
header.
| Class | Purpose |
|---|---|
std::ifstream |
Used for reading from files. |
std::ofstream |
Used for writing to files. |
std::fstream |
Used for both reading and writing. |
To work with files, include the <fstream> header.
#include <fstream>
For example:
#include <iostream>
#include <fstream>
int main() {
std::ofstream file;
return 0;
}
An std::ofstream object is commonly used to write data to
a file.
#include <fstream>
int main() {
std::ofstream file;
file.open("data.txt");
file.close();
return 0;
}
If the operation succeeds, the file can be created or opened for output according to the selected mode.
The insertion operator << can be used to write data
to an output file stream.
#include <fstream>
int main() {
std::ofstream file(
"data.txt"
);
file <<
"Hello C++";
file.close();
return 0;
}
The text is written to data.txt.
#include <fstream>
int main() {
std::ofstream file(
"student.txt"
);
file <<
"Name: Rahul\n";
file <<
"Age: 20\n";
file <<
"Course: C++\n";
file.close();
return 0;
}
The newline character \n can be used to write multiple
lines.
It is good practice to check whether the file was opened successfully.
#include <fstream>
#include <iostream>
int main() {
std::ofstream file(
"data.txt"
);
if(!file) {
std::cout <<
"File could not be opened";
return 1;
}
file <<
"Hello C++";
file.close();
return 0;
}
The std::ifstream class is used to read data from a file.
#include <fstream>
#include <iostream>
int main() {
std::ifstream file(
"data.txt"
);
std::string text;
file >> text;
std::cout <<
text;
file.close();
return 0;
}
The extraction operator >> reads formatted data.
Use std::getline() when you want to read an entire line,
including spaces.
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file(
"data.txt"
);
std::string line;
while(
std::getline(file, line)
) {
std::cout <<
line
<< std::endl;
}
file.close();
return 0;
}
A common pattern for reading a text file is:
std::string line;
while(
std::getline(file, line)
) {
std::cout <<
line
<< std::endl;
}
The loop continues while std::getline() successfully reads
a line.
A file stream can be created first and opened later using
open().
std::ofstream file;
file.open("data.txt");
file <<
"Hello";
file.close();
This approach is useful when the file name or opening operation needs to be controlled separately.
The close() function closes an open file stream.
std::ofstream file(
"data.txt"
);
file <<
"Some data";
file.close();
Closing a file releases the stream's associated resources and finishes the output operation.
C++ provides different file opening modes.
| Mode | Purpose |
|---|---|
std::ios::in |
Open for input. |
std::ios::out |
Open for output. |
std::ios::app |
Append output at the end of the file. |
std::ios::ate |
Open and initially position at the end. |
std::ios::trunc |
Truncate existing output when the mode applies. |
std::ios::binary |
Open in binary mode. |
The std::ios::app mode is used to append output to the end
of a file.
#include <fstream>
int main() {
std::ofstream file(
"data.txt",
std::ios::app
);
file <<
"New line added\n";
file.close();
return 0;
}
Existing file content is preserved while new output is written at the end.
The std::fstream class can be used for both input and
output.
#include <fstream>
int main() {
std::fstream file(
"data.txt",
std::ios::in |
std::ios::out
);
return 0;
}
The exact behavior also depends on the file's existing state and the opening modes used.
File streams maintain positions used for reading and writing. Common functions include:
tellg() – gets the current input position.seekg() – changes the input position.tellp() – gets the current output position.seekp() – changes the output position.std::ifstream file(
"data.txt"
);
std::cout <<
file.tellg();
The tellg() function returns the current input position
of a stream.
std::ifstream file(
"data.txt"
);
std::cout <<
"Position: "
<< file.tellg();
It is useful when working with file positions during input operations.
The seekg() function changes the input position.
std::ifstream file(
"data.txt"
);
file.seekg(0);
std::string line;
std::getline(
file,
line
);
The position can be moved to a desired location before reading.
For output positioning, C++ provides tellp() and
seekp().
std::ofstream file(
"data.txt"
);
file <<
"Hello";
std::cout <<
file.tellp();
file.seekp(0);
These functions are useful when controlling the output position.
A common and reliable pattern for reading text files is to test the actual read operation.
std::string line;
while(
std::getline(file, line)
) {
std::cout <<
line
<< std::endl;
}
Avoid using eof() as the primary loop condition because
end-of-file is normally detected after a read attempt fails.
C++ stream objects provide functions to inspect stream state.
is_open() – checks whether the stream is associated with an open file.good() – indicates that no error state is currently set.fail() – checks for a logical or input/output failure.bad() – checks for a serious stream error.eof() – checks whether the end-of-file state is set.if(file.is_open()) {
std::cout <<
"File is open";
}
#include <fstream>
#include <iostream>
int main() {
std::ofstream file(
"students.txt"
);
if(!file) {
std::cout <<
"Unable to open file";
return 1;
}
file <<
"101 Rahul 85\n";
file <<
"102 Priya 92\n";
file <<
"103 Amit 78\n";
file.close();
return 0;
}
This program stores simple student records in a text file.
#include <fstream>
#include <iostream>
int main() {
std::ifstream file(
"students.txt"
);
if(!file) {
std::cout <<
"Unable to open file";
return 1;
}
int id;
std::string name;
int marks;
while(
file >>
id >>
name >>
marks
) {
std::cout <<
id << " "
<< name << " "
<< marks
<< std::endl;
}
file.close();
return 0;
}
Formatted extraction is useful when the file contains predictable whitespace-separated data.
Binary mode allows a stream to process file data as binary rather than text-oriented data.
#include <fstream>
int main() {
int number = 100;
std::ofstream file(
"data.bin",
std::ios::binary
);
file.write(
reinterpret_cast<const char*>(
&number
),
sizeof(number)
);
file.close();
return 0;
}
Binary files are commonly used when working with raw object representations or specific binary formats. Such representations are not automatically portable or suitable for every type.
<fstream>.eof() incorrectly as the primary read-loop condition.std::getline() when complete text lines are required.#include <iostream>
#include <fstream>
#include <string>
int main() {
{
std::ofstream file(
"students.txt"
);
if(!file) {
std::cout <<
"File could not be opened";
return 1;
}
file <<
"Rahul\n";
file <<
"Priya\n";
file <<
"Amit\n";
}
{
std::ifstream file(
"students.txt"
);
if(!file) {
std::cout <<
"File could not be opened";
return 1;
}
std::string name;
while(
std::getline(
file,
name
)
) {
std::cout <<
name
<< std::endl;
}
}
return 0;
}
The output stream writes student names and the input stream later reads them line by line.
| Concept | Meaning |
|---|---|
std::ifstream |
Used for input from files. |
std::ofstream |
Used for output to files. |
std::fstream |
Used for both input and output. |
open() |
Opens a file stream. |
close() |
Closes the file stream. |
std::getline() |
Reads a complete line from a text stream. |
std::ios::app |
Appends output at the end of a file. |
tellg() / seekg() |
Get or change the input position. |
tellp() / seekp() |
Get or change the output position. |
std::ios::binary |
Opens a stream in binary mode. |
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ofstream out(
"data.txt"
);
if(!out) {
std::cout <<
"Unable to open file";
return 1;
}
out <<
"C++ File Handling";
out.close();
std::ifstream in(
"data.txt"
);
if(!in) {
std::cout <<
"Unable to open file";
return 1;
}
std::string line;
while(
std::getline(in, line)
) {
std::cout <<
line;
}
return 0;
}
File handling allows C++ programs to store and retrieve information from external files. Understanding streams, file modes, reading, writing, and stream states is essential for building applications that work with persistent data.
<fstream> library.std::ifstream is commonly used for reading files.std::ofstream is commonly used for writing files.std::fstream can be used for both reading and writing.std::getline() reads complete lines.std::ios::app is useful for appending data.tellg() and seekg() work with input positions.tellp() and seekp() work with output positions.Question: Which C++ class is commonly used to read data from a file?