Repair a generated file owner

from RAII
C++23 (GCC 13.3.0) advanced 6 min 4 issues to find

Review this generated report-file wrapper and export function.

Own a FILE exclusively, reject open failure, write report text safely, and let callers observe close failure without throwing from destruction.

C++
class ReportFile {
public:
    explicit ReportFile(const char* path)
        : file_(std::fopen(path, "w")) {}
    ~ReportFile() { close(); }
    void write(std::string text) {
        std::fprintf(file_, text.c_str());
    }
    void close() {
        if (file_ && std::fclose(file_) != 0) {
            throw std::runtime_error("close failed");
        }
    }
private:
    std::FILE* file_;
};

void export_report(const std::string& report, const char* path) {
    ReportFile file(path);
    file.write(report);
}

generated code is illustrative, not from any one model

Open in playground
Report an error