CHAPTER 7
File Handling in C++
File streams (ifstream, ofstream,
fstream)
1. ifstream (input file stream)
• A class in C++ used to create input file stream objects,
which are connected to files for reading data.
• Default file mode: ios::in.
• Key point: Only reads, cannot write.
Syntax:
ifstream in("data.txt"); // opens file for reading
2. ofstream (output file stream)
A class in C++ used to create output file stream objects,
which are connected to files for writing data.
• Default file mode: ios::out.
• Key point: Only writes, cannot read.
Syntax:
ofstream out("data.txt"); // opens file for writing
3. fstream (file stream)
• A class in C++ that allows both input (reading) and
output (writing) operations on the same file.
• Default file mode: ios::in | ios::out.
• Key point: Can read and write with one object.
Syntax :
fstream file("data.txt", ios::in | ios::out); // opens for both
Reading from and writing to files/console
1. Write to file
The process of sending data from a program into a file on
disk using ofstream or fstream.
Syntax :
ofstream out("data.txt");
out << "Hello, world!";
out.close();
Example : Writing to a File using
ofstream
#include <iostream>
#include <fstream> // for file handling
using namespace std;
int main() {
ofstream outFile("output.txt"); // create & open file
if (!outFile) {
cout << "Error opening file!" << endl;
return 0;
}
else
{
outFile << "Hello, this is written into the file.\n";
outFile << "C++ file handling is easy!\n";
outFile.close(); // close file
cout << "Data written to output.txt successfully." << endl;
}
return 0;
}
2. Reading from a File
The process of sending data from a program into a file on
disk using ofstream or fstream.
Syntax :
ifstream in("data.txt");
string line;
while (getline(in, line)) cout << line << endl;
Example : Reading from a File using
ifstream
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("output.txt"); // open existing file
string line;
if (!inFile) {
cout << "File not found!" << endl;
return 0;
}
cout << "Reading from file:" << endl;
while (getline(inFile, line)) {
cout << line << endl; // print each line to console
}
inFile.close();
return 0;
}
Example: Using fstream for both Reading & Writing
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file;
// Open file in write mode first
file.open("data.txt", ios::out);
if (!file) {
cout << "Error opening file for writing!" << endl;
return 1;
}
file << "Line 1: C++ is fun.\n";
file << "Line 2: File handling with fstream.\n";
file.close(); // Close after writing
// Open file again in read mode
file.open("data.txt", ios::in);
if (!file) {
cout << "Error opening file for reading!" << endl;
return 1;
}
string line;
cout << "Reading from data.txt:" << endl;
while (getline(file, line)) {
cout << line << endl;
}
file.close(); // Close after reading
return 0;
}
File modes
• When we open a file using file streams (ifstream, ofstream, or
fstream), we can specify modes that decide how the file will be
accessed (read, write, append, etc.).
• These modes are defined in the ios (input/output stream) class as
flags.
Common File Modes:
1. ios::in
• Stands for input mode.
• Opens the file for reading only.
• Default mode for ifstream.
• If the file does not exist → opening will fail.
• Example:
file.open("data.txt", ios::in); // open file for reading
2. ios::out
• Stands for output mode.
• Opens the file for writing only.
• If the file already exists → its contents are erased (overwritten).
• If the file doesn’t exist → a new one is created.
• Default mode for ofstream.
• Example:
• file.open("data.txt", ios::out); // open file for writing
3. ios::app
• Stands for append mode.
• Opens the file for writing.
• Does not erase existing data.
• New data is always added at the end of the file.
Example:
• file.open("data.txt", ios::app); // open file in append mode
4. ios::ate
• Stands for at end.
• Opens the file and places the file pointer at the end .
Example:
• file.open("data.txt", ios::ate); // open and set pointer at end
5. ios::binary
• Opens the file in binary mode (instead of text mode).
• Used when dealing with images, videos, or binary data.
• By default, files are opened in text mode.
Example:
• file.open("data.bin", ios::out | ios::binary); // write binary file
6. ios::trunc
• Stands for truncate.
• If the file already exists, its contents are deleted when
opened.
• Usually happens automatically when using ios::out, unless
combined with ios::app.
Example:
• file.open("data.txt", ios::out | ios::trunc);
1. Text File Operations
A text file stores data in human-readable form (characters).
Example: .txt file.
Data is stored as plain text using ASCII or Unicode.
Use: Good for storing simple data like names, numbers,
messages, etc.
Example :
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a text file
ofstream outFile("data.txt");
outFile << "Hello, this is a text file!" << endl;
outFile << 123 << endl;
outFile.close();
// Reading from a text file
ifstream inFile("data.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return 0;
}
2. Binary File Operations
• Definition: A binary file stores data in the same way it is
stored in memory (0s and 1s).
• Data is not human-readable. It’s written as raw bytes.
• Use: Good for images, audio, video, and complex data
structures.
• Syntax:
ifstream inFile("number.dat", ios::binary);
inFile.read((char*)&n, sizeof(n));
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num = 123;
// Writing to binary file
ofstream outFile("number.dat", ios::binary);
outFile.write((char*)&num, sizeof(num));
outFile.close();
// Reading from binary file
int n;
ifstream inFile("number.dat", ios::binary);
inFile.read((char*)&n, sizeof(n));
inFile.close();
cout << "Number read from file: " << n << endl;
return 0;
}
Difference between Text file and Binary
file
Text File Binary File
In a text file, data is stored as
In a binary file, data is stored in raw
human-readable characters using ASCII
memory bytes as 0s and 1s.
or Unicode.
Text files can be opened and read directly Binary files cannot be read directly in
in editors like Notepad or VS Code. editors and appear as garbage if opened.
The size of a text file is usually larger The size of a binary file is usually smaller
because each character occupies because data is stored in its native binary
memory as bytes. format.
Reading and writing text files is slower for Reading and writing binary files is faster
large data because the program must because the data is stored and retrieved
convert between text and memory. directly in memory format.
Text files are suitable for storing simple Binary files are suitable for storing
text, numbers as text, logs, or complex data such as images, audio,
configuration files. video, or serialized objects.
An example in C++ of a binary file is:
An example in C++ of a text file is:
ofstream out("data.dat", ios::binary);
ofstream out("data.txt"); out << 123;.
out.write((char*)&num, sizeof(num));.
Command Line Argument
• A command line argument is a value (data) that is passed to a
program at the time of execution through the command line
(terminal or command prompt), instead of taking input during
program execution.
• These arguments are passed to the main() function in the form of:
int main(int argc, char* argv[])
• argc (argument count):
An integer that represents the total number of arguments passed,
including the program name.
• argv (argument vector):
An array of character pointers (C-strings) that stores each argument
as a string.
Example:
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "Number of arguments: " << argc << endl;
for (int i = 0; i < argc; i++) {
cout << "Argument " << i << ": " << argv[i] << endl;
}
return 0;
}
• We use command line arguments because they make
programs automated, reusable, and convenient by
allowing inputs to be passed at execution time, instead of
asking interactively during runtime.
File Pointers
• When we read/write files in C++, the system needs to
know where in the file we are currently reading/writing.
This position is maintained by an internal file pointer.
There are two pointers:
• get pointer (input pointer) → used for reading from a
file.
• put pointer (output pointer) → used for writing into a file.
• Both pointers move automatically as you read/write, but
you can also manipulate them manually using special
functions.
Functions for Manipulating File Pointers
1. tellg()
• Tells the current position of the get (input) pointer in a file.
• Returns position in terms of number of bytes from the beginning.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("data.txt");
cout << "Current position (get): " << fin.tellg() << endl;
string word;
fin >> word; // read first word
cout << "After reading: " << fin.tellg() << endl;
fin.close();
}
2. tellp()
• Tells the current position of the put (output) pointer in a file.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fout("data.txt");
fout << "Hello ";
cout << "Current position (put): " << fout.tellp() << endl;
fout << "World";
cout << "After writing: " << fout.tellp() << endl;
fout.close();
}
3. seekg(position, direction)
• Used to move the get pointer (input pointer).
Syntax:
file.seekg(offset, direction);
• offset = number of bytes to move.
direction can be:
• ios::beg → beginning of file
• ios::cur → current position
• ios::end → end of file
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("data.txt");
cout << "Initial position: " << fin.tellg() << endl;
// Move 6 bytes from beginning (skip "Hello ")
fin.seekg(6, ios::beg);
cout << "After seekg(6, beg): " << fin.tellg() << endl;
string word;
fin >> word; // should read "World"
cout << "Word read: " << word << endl;
// Move back 5 bytes from current position
fin.seekg(-5, ios::cur);
cout << "After seekg(-5, cur): " << fin.tellg() << endl;
fin >> word; // read again from there
cout << "Word read again: " << word << endl;
// Move 5 bytes before end of file
fin.seekg(-3, ios::end);
cout << "After seekg(-3, end): " << fin.tellg() << endl;
fin >>word ;
cout<<"Word : "<<word<<endl;
fin.close();
}
4. seekp(position, direction)
• Used to move the put pointer (output pointer).
• Same arguments as seekg().
Example :
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream fout("data.txt", ios::in | ios::out); // open for both read & write
if (!fout.is_open()) {
cout << "Error: Could not open file!" << endl;
return 0;
}
cout << "Initial put pointer: " << fout.tellp() << endl;
// Move 6 bytes from beginning (skip "Hello ")
fout.seekp(6, ios::beg);
cout << "After seekp(6, beg): " << fout.tellp() << endl;
// Overwrite "World" with "Nepal"
fout << "Nepal";
cout << "After writing 'Nepal', put pointer: " << fout.tellp() << endl;
fout.close();
return 0;
}
The End