RAII file handling in C++
CppThe 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), {});
}