C++ File Handling
In C++, file handling allows you to work with files on the disk. It involves reading from and writing to files, which is essential for persistent storage, saving data between program executions, or processing large amounts of data.
C++ provides various classes in the <fstream> library to perform file operations:
ifstream
: Used for reading files.ofstream
: Used for writing files.fstream
: Used for both reading and writing files.These classes are part of the C++ Standard Library, and file streams are used to interact with files on the system.
open()
function or the constructor to open a file.ifstream
or fstream
for reading.ofstream
or fstream
for writing.close()
function to close a file when done.This simple example demonstrates how to open a file and write to it using ofstream
.
#include <iostream>
#include <fstream> // Required for file handling
int main() {
// Create an ofstream object for output
std::ofstream outfile("example.txt"); // Open file for writing
// Check if the file opened successfully
if (outfile.is_open()) {
// Write data to the file
outfile << "Hello, this is a test file!\n";
outfile << "This is the second line of text.\n";
outfile << "C++ File handling is powerful!\n";
outfile.close(); // Close the file after writing
std::cout << "Data written to file successfully." << std::endl;
} else {
std::cout << "Error opening the file." << std::endl;
}
return 0;
}
Explanation:
ofstream
object is used to open the file "example.txt"
for writing.is_open()
function checks if the file was opened successfully.<<
operator.close()
function.This example shows how to open and read data from a file using ifstream.
#include <iostream>
#include <fstream> // Required for file handling
#include <string>
int main() {
// Create an ifstream object for input
std::ifstream infile("example.txt"); // Open the file for reading
// Check if the file opened successfully
if (infile.is_open()) {
std::string line;
// Read the file line by line
while (getline(infile, line)) {
std::cout << line << std::endl; // Print each line to console
}
infile.close(); // Close the file after reading
} else {
std::cout << "Error opening the file." << std::endl;
}
return 0;
}
Explanation:
ifstream
object is used to open the file "example.txt"
for reading.getline()
function is used to read each line of the file and store it in a string.infile.close()
once the reading is done.Output:
Hello, this is a test file!
This is the second line of text.
C++ File handling is powerful!
fstream
(Reading and Writing)The fstream
class is used for both reading and writing to a file. This example demonstrates how to open a file for both operations.
#include <iostream>
#include <fstream>
int main() {
// Create an fstream object for both reading and writing
std::fstream file("example.txt", std::ios::in | std::ios::out); // Open file for input and output
// Check if the file opened successfully
if (file.is_open()) {
std::string line;
// Read the existing contents of the file
std::cout << "Reading from file:\n";
while (getline(file, line)) {
std::cout << line << std::endl;
}
// Move the file pointer to the end to write data
file.clear(); // Clear EOF flag
file.seekp(0, std::ios::end); // Move the pointer to the end of the file
// Write new data to the file
file << "This is a new line added to the file.\n";
file.close(); // Close the file after reading and writing
std::cout << "Data written to file successfully." << std::endl;
} else {
std::cout << "Error opening the file." << std::endl;
}
return 0;
}
Explanation:
fstream
object is created for both reading (std::ios::in
) and writing (std::ios::out
).seekp()
to append new data after reading the existing file contents.clear()
function is used to clear the EOF flag, which is set when the end of the file is reached.<<
operator.Sometimes, you may want to check whether a file exists before trying to open it. You can do this by checking if the file stream was successfully opened.
#include <iostream>
#include <fstream>
int main() {
std::ifstream infile("example.txt"); // Try opening the file for reading
// Check if the file exists and can be opened
if (!infile) {
std::cout << "The file does not exist or could not be opened." << std::endl;
} else {
std::cout << "The file was opened successfully!" << std::endl;
infile.close(); // Close the file after checking
}
return 0;
}
Explanation:
ifstream
object. If the file does not exist, the condition !infile
will be true, and an error message will be displayed.C++ also allows you to read and write files in binary mode. This is useful when you want to store data in its raw form.
#include <iostream>
#include <fstream>
struct Person {
char name[50];
int age;
};
int main() {
Person p1 = {"John Doe", 30};
// Write the struct to a binary file
std::ofstream outfile("person.dat", std::ios::binary);
if (outfile.is_open()) {
outfile.write(reinterpret_cast<char*>(&p1), sizeof(Person));
outfile.close();
std::cout << "Data written to binary file." << std::endl;
}
// Read the struct from the binary file
std::ifstream infile("person.dat", std::ios::binary);
Person p2;
if (infile.is_open()) {
infile.read(reinterpret_cast<char*>(&p2), sizeof(Person));
infile.close();
std::cout << "Name: " << p2.name << "\nAge: " << p2.age << std::endl;
}
return 0;
}
Explanation:
Person
structure is written to and read from a binary file using std::ios::binary
.reinterpret_cast
is used to treat the structure as a block of raw memory when writing or reading the file.