File handling in C++ allows you to work with files on your computer's storage. You can read data from files, write data to files, and perform various operations like creating, opening, closing, and deleting files.
To work with a file in C++, you first need to open it. You can do this using the ifstream
(input file stream) for reading and ofstream
(output file stream) for writing.
#include
#include
int main() {
std::ifstream inFile; // Input file stream
inFile.open("example.txt"); // Open the file
// Check if the file is opened successfully
if (!inFile) {
std::cerr << "Unable to open file";
return 1; // Exit the program with an error
}
// File is opened successfully, you can now read from it
inFile.close(); // Don't forget to close the file when done
return 0;
}
<iostream>
and <fstream>
for input and output stream operations and file handling respectively.ifstream
object inFile
is declared to handle input operations.open()
member function to open the file named “example.txt” in the current directory.close()
member function.Once the file is successfully opened, you can read data from it. The most common way to do this is by using input stream operators (>>
) to extract data from the file.
#include
#include
#include
int main() {
std::ifstream inFile; // Input file stream object
inFile.open("example.txt"); // Open the file
if (!inFile) {
std::cerr << "Unable to open file";
return 1;
}
std::string data;
while (inFile >> data) { // Read data from file
std::cout << data << std::endl; // Output data to console
}
inFile.close(); // Close the file
return 0;
}
// output //
This
is
an
example
file.
while
loop, data is read from the file using the input stream operator >>
. This reads the data word by word, separated by whitespace, and stores it in the string variable data
.cout
.This output demonstrates that the contents of the “example.txt” file were successfully read and printed to the console, each word on a new line.
Similarly, you can write data to a file using the ofstream
class and output stream operators (<<
).
#include
#include
int main() {
std::ofstream outFile; // Output file stream object
outFile.open("output.txt"); // Open (or create) the file named "output.txt"
if (!outFile) {
std::cerr << "Unable to create file";
return 1;
}
outFile << "Hello, world!\n"; // Write data to the file
outFile << "This is a new line.";
outFile.close(); // Close the file
return 0;
}
// output //
Hello, world!
This is a new line.
ofstream
object outFile
to handle output operations.open()
member function is used to create or open the file named “output.txt” in the current directory for writing.<<
. In this case, we’re writing the string “Hello, world!\n” followed by “This is a new line.” to the file.close()
member function.After running the program, you’ll find a file named “output.txt” in the same directory with the following content:
You can check if you have reached the end of a file while reading from it using the eof()
function.
#include
#include
#include
int main() {
std::ifstream inFile;
inFile.open("example.txt");
if (!inFile) {
std::cerr << "Unable to open file";
return 1;
}
std::string data;
while (!inFile.eof()) {
inFile >> data;
std::cout << data << std::endl;
}
inFile.close();
return 0;
}
You can append data to an existing file by opening it in append mode (std::ios::app
).
#include
#include
int main() {
std::ofstream outFile;
outFile.open("output.txt", std::ios::app);
if (!outFile) {
std::cerr << "Unable to open file";
return 1;
}
outFile << "\nAppending new data.";
outFile.close();
return 0;
}
In addition to text files, you can also work with binary files in C++. Binary files store data in a format that is not human-readable but is more efficient for certain types of data.
#include
#include
struct Person {
char name[50];
int age;
};
int main() {
Person p1 = {"John", 25};
// Writing to a binary file
std::ofstream outFile("people.bin", std::ios::binary);
outFile.write(reinterpret_cast(&p1), sizeof(Person));
outFile.close();
// Reading from a binary file
Person p2;
std::ifstream inFile("people.bin", std::ios::binary);
inFile.read(reinterpret_cast(&p2), sizeof(Person));
inFile.close();
std::cout << "Name: " << p2.name << ", Age: " << p2.age << std::endl;
return 0;
}
// output //
Name: John, Age: 25
File handling in C++ is a powerful feature that allows you to work with files effectively. You can read data from files, write data to files, and perform various operations on files. Understanding file handling is essential for many real-world applications where data needs to be stored and manipulated. Happy coding !❤️