C++ fstream Class šŸ“

beginner
11 min

C++ fstream Class šŸ“

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.

What is the 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.

Key Concepts šŸŽÆ

  • File Stream Types šŸ“: fstream provides four types of file streams: fstream, ifstream, ofstream, and ofstream_append. Each type is used for specific operations:
    • fstream: Both reading and writing
    • ifstream: Only reading
    • ofstream: Only writing
    • ofstream_append: Writing to the end of an existing file

Creating a File Stream šŸ“

To 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:

cpp
#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.

Writing to a File šŸŽÆ

Now that you have a file stream, you can write data to the file:

cpp
#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 šŸŽÆ

Reading from a file involves creating an ifstream object and reading the content into a variable:

cpp
#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.

Quick Quiz
Question 1 of 1

Which file stream class can be used for both reading and writing operations?

Happy coding! šŸ¤–šŸŽ‰