Welcome to our deep dive into the C++ fstream class! In this comprehensive guide, we'll explore the world of file handling with the fstream class, a powerful tool for reading from and writing to files in your C++ projects.
fstream Class? š”The fstream class is a part of the standard C++ library and stands for "file stream." It's a stream that can be used to perform I/O (Input/Output) operations on files, just like the istream and ostream classes handle input and output for console streams.
fstream provides four types of file streams: fstream, ifstream, ofstream, and ofstream_append. Each type is used for specific operations:
fstream: Both reading and writingifstream: Only readingofstream: Only writingofstream_append: Writing to the end of an existing fileTo work with a file, you first need to create a file stream. Here's how to create an ofstream object for writing to a file:
#include <fstream>
int main() {
std::ofstream myFile("example.txt");
// Continue working with 'myFile'...
}In the example above, we include the fstream library, create an ofstream object called myFile, and open a file called example.txt for writing.
Now that you have a file stream, you can write data to the file:
#include <fstream>
#include <iostream>
int main() {
std::ofstream myFile("example.txt");
if (myFile.is_open()) {
myFile << "Hello, World!\n";
myFile << "This is an example file.\n";
myFile.close();
} else {
std::cerr << "Unable to open file example.txt\n";
}
return 0;
}In this example, we check if the file is open before writing to it. If the file is open, we write two lines to the file and close it.
Reading from a file involves creating an ifstream object and reading the content into a variable:
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream myFile("example.txt");
if (myFile.is_open()) {
std::string line;
while (getline(myFile, line)) {
std::cout << line << "\n";
}
myFile.close();
} else {
std::cerr << "Unable to open file example.txt\n";
}
return 0;
}In this example, we open the file, read each line into a string variable called line, and print it to the console.
Which file stream class can be used for both reading and writing operations?
Happy coding! š¤š