审查这个生成式报表文件包装器与导出函数。
独占 FILE,拒绝打开失败,安全写入报表文本,让调用方能观察关闭失败,同时不从析构函数抛出。
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);
}
生成代码仅作示例,不代表任何特定模型