C++ - File Handling
C++ - File Handling
File Handling in C++ refers to reading from and writing to files, enabling permanent storage of data
beyond program execution.
Importance of File Handling in C++
File handling in C++ is essential for storing, retrieving, and managing data efficiently. It allows
programs to read from and write to files, making data persistent beyond program execution. Below
are the key reasons why file handling is important in C++:
1️. Data Persistence
Unlike variables (which store data temporarily in RAM), files store data permanently on
disk.
Ensures that data remains accessible even after the program exits.
Example: Saving user scores in a game so they remain after closing the application.
2️. Large Data Storage & Processing
Memory (RAM) is limited, but files provide virtually unlimited storage.
Allows processing of large datasets that cannot fit into RAM.
Example: A banking system storing thousands of transaction records.
3️. Data Sharing & Communication
Files allow data exchange between different programs or users.
Standard file formats (.txt, .csv, .json, .xml) enable compatibility across platforms.
Example: Exporting a report in CSV format to be opened in Excel.
4️. Logging & Debugging
Programs can log important events and errors in a file for later analysis.
Helps in debugging and monitoring software performance.
Example: Web servers maintain log files to track website requests.
int main() {
ofstream file("example.txt"); // Create and open a text file
file << "Hello, File Handling in C++"; // Write data
file.close(); // Close the file
return 0;
}
int main() {
ofstream file("data.bin", ios::binary); // Open file in binary mode
int number = 1️00;
file.write(reinterpret_cast<char*>(&number), sizeof(number)); //
Write binary data
file.close();
ifstream readFile("data.bin", ios::binary); // Open binary file for
reading
int readNumber;
readFile.read(reinterpret_cast<char*>(&readNumber),
sizeof(readNumber));
cout << "Read from file: " << readNumber << endl;
readFile.close();
return 0;
}
File Stream Classes in C++
• C++ provides a set of file stream classes in the <fstream> header for handling file
input and output operations.
• These classes enable programs to read data from files and write data to files,
making file storage and retrieval easy.
• File handling is crucial for storing structured data, saving user input, logging
system activities, and managing databases.
Types of File Stream Classes
C++ provides three main file stream classes for handling different file operations.
Class Purpose Example Usage
ifstream Used for reading from a file ifstream inFile("data.txt");
ofstream Used for writing to a file ofstream outFile("output.txt");
fstream Used for both reading & writing `fstream file("data.txt", ios::in
int main() {
ofstream file("example.txt"); // Open file for writing
if (file.is_open()) {
cout << "File opened successfully!" << endl;
} else {
cout << "Error opening file!" << endl;
}
file.close(); // Close the file
return 0;
}
int main() {
ofstream outFile("output.txt"); // Open file for writing
outFile << "Hello, C++ File Handling!" << endl;
outFile << "Writing data to a file is simple." << endl;
int main() {
ifstream inFile("data.txt"); // Open file for reading
string line;
int main() {
ifstream file("data.txt", ios::in); // Open file for reading
if (!file) {
cout << "Error: File does not exist!" << endl;
return 1;
}
string content;
while (getline(file, content)) {
cout << content << endl;
}
file.close();
return 0;
}
int main() {
ofstream file("output.txt", ios::out); // Open file for writing (overwrite mode)
file << "This is a new file.\n";
file << "Previous content (if any) is erased!\n";
file.close();
return 0;
}
Note: Existing data is deleted when the file is opened.
int main() {
ofstream file("output.txt", ios::app); // Open file in append mode
file << "New line added at the end.\n";
file.close();
return 0;
}
Note: Existing content is preserved, and new data is added at the end.
Example
C++ program to copy the contents of one file into another using file handling:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string sourceFile, destinationFile;