What is the difference between ifstream and ofstream

In C++, there are different types of streams used to perform various operations. Among these streams, the ifstream and ofstream are the most commonly used for reading and writing to files respectively.

ifstream

  • ifstream stands for input file stream. It is used to read data from a file. It provides an interface to read the file using different types of data. Here is an example of how to use ifstream:
1 #include <iostream>
2 #include <fstream>
3
4int main() {
5 std::ifstream inputFile("input.txt"); // open the file for reading
6 std::string line;
7
8 if (inputFile.is_open()) {
9 while (getline(inputFile, line)) { // read the file line by line
10 std::cout << line << std::endl;
11 }
12 inputFile.close(); // close the file
13 } else {
14 std::cout << "Unable to open the file." << std::endl;
15 }
16
17 return 0;
18}

ofstream

  • ofstream stands for output file stream. It is used to write data to a file. It provides an interface to write the file using different types of data. Here is an example of how to use ofstream:
1 #include <iostream>
2 #include <fstream>
3
4int main() {
5 std::ofstream outputFile("output.txt"); // open the file for writing
6
7 if (outputFile.is_open()) {
8 outputFile << "Hello, World!" << std::endl; // write to the file
9 outputFile.close(); // close the file
10 } else {
11 std::cout << "Unable to open the file." << std::endl;
12 }
13
14 return 0;
15}

Both ifstream and ofstream are derived from the std::istream and std::ostream classes respectively. Therefore, they share some common methods like open()close()is_open(), and various insertion (<<) and extraction (>>) operators.

Diferences

ifstream and ofstream are two types of file streams provided by the C++ Standard Library to perform file input and output operations respectively.

  • ifstream: It stands for input file stream. This class is used to handle input tasks associated with the stream. For example, it can be used to read data from a file.

  • ofstream: It stands for output file stream. This class is used to handle output tasks associated with the stream. For example, it can be used to write data to a file.

The code above demonstrates the use of ifstream (for reading from a file) and ofstream (for writing to a file) in C++.

Related posts:

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading