In C++, there are several ways to read and write to files. Here's an example of
how to read and write to a file using the C++ standard library's fstream library,
which is considered a more recent and optimized way of performing file I/O
operations:
Copy code
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a file
ofstream out_file("example.txt");
if (out_file.is_open()) {
out_file << "Writing this to a file.\n";
out_file.close();
} else {
cout << "Unable to open file for writing." << endl;
}
// Reading from a file
string line;
ifstream in_file("example.txt");
if (in_file.is_open()) {
while (getline(in_file, line)) {
cout << line << endl;
}
in_file.close();
} else {
cout << "Unable to open file for reading." << endl;
}
return 0;
}
This code uses the ofstream class to open the file "example.txt" for writing, and
the ifstream class to open the same file for reading. The out_file.is_open() and
in_file.is_open() checks are used to ensure that the files were opened successfully.
The out_file << "Writing this to a file.\n"; writes the string "Writing this to
a file." to the file and the getline(in_file, line) reads the content of the file
line by line and stores it in the string "line".
Please note that if the file specified in the ofstream or ifstream constructor
does not exist, it will create a new file with that name. If you want to append
to an existing file, you can use ofstream with ios::app flag.
Also, you can use C++ standard library's stringstream and iostream to read
and write the file, which are optimized for reading and writing large amounts of
data.
To embed this project on your website, copy the following code and paste it into your website's HTML: