In C++, file handling allows you to work with files for reading from and writing to external files. This is useful when you need to store data persistently or retrieve data from existing files.
To work with files in C++, you will need to include the
To write data to a file, you will need to create an ofstream
object, which stands for output file stream. You can then use the object to open the file using the open()
function, specifying the file name as the argument.
Once the file is opened, you can use the output stream operator <<
to write data to the file. For example, you can write a string to the file by using outputFile << "Hello, AlgoDaily!"
.
After writing the data, make sure to close the file using the close()
function of the ofstream
object.
To read data from a file, you will need to create an ifstream
object, which stands for input file stream. Similar to writing, you can use the open()
function to open the file for reading.
To read data from the file, you can use the input stream operator >>
. For example, you can read a string from the file by using inputFile >> data;
, where data
is a string variable.
After reading the data, make sure to close the file using the close()
function of the ifstream
object.
Here's an example code that demonstrates file handling in C++:
1#include <iostream>
2#include <fstream>
3
4using namespace std;
5
6int main() {
7 // Create a file
8 ofstream outputFile;
9 outputFile.open("data.txt");
10
11 // Write data to the file
12 outputFile << "Hello, AlgoDaily!";
13
14 // Close the file
15 outputFile.close();
16
17 // Read data from the file
18 ifstream inputFile;
19 inputFile.open("data.txt");
20
21 string data;
22 inputFile >> data;
23
24 // Print the data
25 cout << "Data read from the file: " << data << endl;
26
27 // Close the file
28 inputFile.close();
29
30 return 0;
31}
xxxxxxxxxx
}
using namespace std;
int main() {
// Create a file
ofstream outputFile;
outputFile.open("data.txt");
// Write data to the file
outputFile << "Hello, AlgoDaily!";
// Close the file
outputFile.close();
// Read data from the file
ifstream inputFile;
inputFile.open("data.txt");
string data;
inputFile >> data;
// Print the data
cout << "Data read from the file: " << data << endl;
// Close the file
inputFile.close();