Today we’re going to talk about file handling in C++. You’ll learn how to read from and write to files using a special library called fstream.
To get started, you’ll need to include a header file at the beginning of your code.
#include
Next let’s talk about file streams. There are three main types you’ll work with:
ofstreamfor writing to filesifstreamfor reading from themfstream, which allows you to do both reading and writing in one stream.
If you want to write something to a file, here’s a simple example:
#include
#include
int main() {
std::ofstream fout("example.txt");
fout << "Hello, this is Day 19!\n";
fout.close();
return 0;
}
And if you want to read from a file, you’d do it like this:
#include
#include
using namespace std;
int main() {
std::ifstream fin("example.txt");
string line;
while (getline(fin, line)) {
std::cout << line << endl;
}
fin.close();
return 0;
}
There are also different opening modes you can use, such as ios::in for reading and ios::out for writing. Some others include ios::app for appending, ios::binary for binary files, and ios::trunc, which truncates files.
It’s also important to check if a file opened correctly. For instance:
std::ifstream fin_stream("data.txt");
if (!fin_stream) {
std::cout << "File could not be opened!";
}
For practice, you could try creating a program that saves what the user types into a file, then reads that back and displays it on the screen. And remember, it’s a good habit to close your files using .close() when you’re done to avoid any issues. Happy coding!
Comments
Post a Comment