Menu
Coddy logo textTech

Working with fstream

Lesson 14 of 23 in Coddy's C++ File Handling course.

Instead of using ifstream to read from a file and ofstream to write to the file, we can simply use the fstream class for all file operations.

The constructor for fstream allows you to specify the file name and the mode for file operations. So, we can choose to input or output with an object from the same class.

  • ios::in - opens the file for reading
  • ios::out - opens the file for writing
fstream output("example.txt", ios::out); // Write mode
output << "File Handling in C++" << endl;
output.close();

// Reading from the same file
fstream input("example.txt" ios::in) // Read mode
string line;
getline(input, line);
cout << line << endl;
Output:
File Handling in C++

As you can see, we use an object from the same class just opened in a different mode to first write and then read from the same file.

challenge icon

Challenge

Easy

Input from the file input.txt print out its contents on standard output using an object from the fstream class instead of the ifstream

Try it yourself

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    
    // Enter  your code here
    
    return 0;
}

All lessons in C++ File Handling