RAII file handling in C++

Cpp

The stream closes itself when it leaves scope, whether the function returns normally or throws.

#include <fstream>
#include <string>

std::string read_all(const std::string& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) throw std::runtime_error("cannot open " + path);
    return std::string(std::istreambuf_iterator<char>(in), {});
}

More in Systems

Random picks