File Handling in C++
File handling is an essential aspect of programming that allows you to read from and write to files. In C++, you can perform file handling operations using the file stream objects provided by the standard library. These stream objects, namely ifstream (input file stream) and ofstream (output file stream), allow you to interact with files seamlessly. In this lesson, we'll explore how to handle files in C++ and perform common file operations such as reading from a file and writing to a file.
Opening a File
Before you can read from or write to a file, you need to open it. You can use the file stream objects and the
open()
function to open a file. You need to specify the file name and the mode (input, output, or both) as parameters to the
open()
function.
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile;
outputFile.open("output.txt"); // Open a file for writing
std::ifstream inputFile;
inputFile.open("input.txt"); // Open a file for reading
// Perform file operations here...
outputFile.close(); // Close the output file
inputFile.close(); // Close the input file
return 0;
}
Reading from a File
To read data from a file, you can use the
ifstream
object and various input stream functions like
getline()
and
>>
. You can read data line by line or extract specific data using appropriate variables and data types.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile;
inputFile.open("input.txt"); // Open the input file
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl; // Print each line
}
inputFile.close(); // Close the input file
return 0;
}
Writing to a File
To write data to a file, you can use the
ofstream
object and the output stream operator (
<<
). You can write data to a file using various data types and format it as needed.
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile;
outputFile.open("output.txt"); // Open the output file
outputFile << "Hello, File Handling in C++!" << std::endl;
outputFile << 42 << std::endl;
outputFile.close(); // Close the output file
return 0;
}
Conclusion
File handling is an important aspect of programming, and in C++, you can easily handle files using the file stream objects provided by the standard library. Opening, reading, and writing to files are common file operations that you can perform using the appropriate file stream objects and stream operators. Understanding file handling in C++ allows you to work with external data and create programs that can store and retrieve information from files.