C++ File Handling: fstream, ifstream and ofstream

C++ reads and writes files with streams, the same way as cout and cin. Include <fstream>.

ClassUse
std::ofstreamOutput file stream: write
std::ifstreamInput file stream: read
std::fstreamBoth

Write and read

#include <fstream>
#include <iostream>
#include <string>

int main() {
    {
        std::ofstream out("notes.txt");
        out << "C++ is fast.\n";
        out << "Files are easy.\n";
    }                                       // the file is closed here by the destructor (RAII)

    std::ifstream in("notes.txt");
    std::string line;
    int number = 0;
    while (std::getline(in, line)) {
        std::cout << ++number << ": " << line << '\n';
    }
}
Output

1: C++ is fast.
2: Files are easy.

Append and check errors

#include <fstream>
#include <iostream>

int main() {
    std::ofstream out("log.txt", std::ios::app);          // append mode
    out << "first\n";
    out.close();
    std::ofstream again("log.txt", std::ios::app);
    again << "second\n";
    again.close();

    std::ifstream in("log.txt");
    std::cout << in.rdbuf();                              // print the whole file

    std::ifstream missing("no-such-file.txt");
    if (!missing) {
        std::cout << "Could not open the file\n";
    }
}
Output

first
second
Could not open the file

Read words and numbers

#include <fstream>
#include <iostream>

int main() {
    std::ofstream("numbers.txt") << "10 20 30 40";
    std::ifstream in("numbers.txt");
    int n, total = 0;
    while (in >> n) {
        total += n;
    }
    std::cout << "Total: " << total << '\n';
}
Output

Total: 100

std::filesystem (C++17)

#include <filesystem>
#include <fstream>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    fs::create_directories("project/docs");
    std::ofstream("project/docs/readme.txt") << "Hello";
    std::ofstream("project/main.txt") << "Main";

    for (const auto& entry : fs::recursive_directory_iterator("project")) {
        std::cout << entry.path().generic_string() << (entry.is_directory() ? " (dir)" : "") << '\n';
    }
    std::cout << fs::file_size("project/main.txt") << " bytes\n";
    std::cout << fs::exists("project/none.txt") << '\n';
    fs::remove_all("project");
}
Output

project/main.txt
project/docs (dir)
project/docs/readme.txt
4 bytes
0

Note: Streams close the file in the destructor, so you rarely need to call close(). Always check if the file opened. Next: C++ Move Semantics and the Rule of Five.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.