File Handling
File handling in C++ involves reading from and writing to files. This is useful for tasks such as storing data, reading configuration files, or processing large datasets.
To perform file handling operations in C++, include the <fstream>
library. Here's an example program that demonstrates how to write to and read from a file:
1{{code}}
In this example:
We use the
ofstream
class to write data to a file. First, we create anofstream
object and open the file using theopen()
function. Then, we use the<<
operator to write the string "Hello, World!" to the file. Finally, we close the file using theclose()
function.We use the
ifstream
class to read data from a file. First, we create anifstream
object and open the file using theopen()
function. Then, we use thegetline()
function in a loop to read each line of the file and print it to the console. Finally, we close the file using theclose()
function.
You can run the above program and observe the output to see the results of the file handling operations. Feel free to experiment and modify the code to further explore file handling in C++.
xxxxxxxxxx
using namespace std;
int main() {
// Writing to a file
ofstream outfile;
outfile.open("example.txt");
outfile << "Hello, World!";
outfile.close();
// Reading from a file
ifstream infile;
string line;
infile.open("example.txt");
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
return 0;
}