RAII file reader that closes on scope exit
C++
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// Owns an ifstream and closes it when the object leaves scope.
class FileReader {
public:
explicit FileReader(const std::string& path) : in_(path) {
if (!in_) {
throw std::runtime_error("cannot open " + path);
}
}
FileReader(const FileReader&) = delete;
FileReader& operator=(const FileReader&) = delete;
std::vector<std::string> lines() {
std::vector<std::string> out;
for (std::string line; std::getline(in_, line);) {
out.push_back(std::move(line));
}
return out;
}
private:
std::ifstream in_;
};
int main() {
try {
FileReader reader("notes.txt");
for (const auto& line : reader.lines()) {
std::cout << line << '\n';
}
} catch (const std::exception& error) {
std::cerr << "error: " << error.what() << '\n';
return 1;
}
}