CodeBlanks Logo Icon CodeBlanks

std::fstream

Learn to both read and write with std::fstream.

std::fstream in one class

std::fstream is used for both reading and writing. You specify the mode with std::ios::in and std::ios::out flags.

Example: std::fstream fs("data.txt", std::ios::out); opens the file for writing. After writing and closing, fs.open("data.txt", std::ios::in); reopens the same object for reading. So a single fs object can both write and read. std::ios::trunc erases content, std::ios::app appends. You can combine flags with |.

Write and read with the same object

You can use a std::fstream object first for writing, then for reading. A close() and open() call in between switches the mode.

Example: fs.open("data.txt", std::ios::out); to write, fs.close(); to close. Then fs.open("data.txt", std::ios::in); to read. This is practical for programs that write data to a file and then process it. Using two separate objects (std::ifstream and std::ofstream) is also possible; std::fstream combines them under one roof.

Practice Write and read with std::fstream

Use a single std::fstream object. First open it in std::ios::out mode, write "Hello" and close it. Then reopen in std::ios::in mode, read one word with >> and print it with std::cout.

Starter code

main.cpp
#include <iostream>
#include <fstream>
#include <string>

int main() {
    // Write with std::fstream, close, then read

    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::fstream fs("data.txt", std::ios::out);
    fs << "Hello";
    fs.close();
    fs.open("data.txt", std::ios::in);
    std::string w;
    fs >> w;
    std::cout << w;
    return 0;
}

Expected output

Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each mode to its role

Term Meaning
std::ios::in Reading
std::ios::out Writing
std::ios::app Appending
std::ios::trunc Erasing content

2 Specify the write mode

Question
std::fstream fs("data.txt", std::ios::____);
Answer
std::fstream fs("data.txt", std::ios::out);

Explanation: std::ios::out opens in write mode.

3 What is std::fstream used for?

main.cpp
std::fstream fs("data.txt");
  • Reading only
  • Writing only
  • Deleting files only
  • Both reading and writing Correct answer

Explanation: std::fstream is used for both reading and writing.

All lessons in Intermediate