你可以使用文件系统库 <filesystem>
来检测文件是否存在,并根据结果来创建或打开文件。下面是一个示例代码:
#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string redfishEventLogFile = "example.txt";
if (!fs::exists(redfishEventLogFile)) {
// 文件不存在,创建新文件
std::ofstream outputFile(redfishEventLogFile);
if (outputFile.is_open()) {
outputFile << "Hello, World!" << std::endl;
outputFile.close();
std::cout << "文件已创建并写入内容" << std::endl;
} else {
std::cerr << "无法创建文件" << std::endl;
return 1;
}
} else {
// 文件已存在,追加内容
std::ofstream outputFile(redfishEventLogFile, std::ios::app);
if (outputFile.is_open()) {
outputFile << "Hello again!" << std::endl;
outputFile.close();
std::cout << "文件已打开并追加内容" << std::endl;
} else {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
}
return 0;
}
在这个示例中,首先使用 std::filesystem
的 exists()
函数检查指定的文件是否存在。如果文件不存在,则通过 std:ofstream
创建一个新的输出流,并写入一些内容;如果文件已经存在,则以附加模式(std:ios:app
) 打开输出流,并追加内容。
请注意,在编译和运行代码之前,确保你的编译环境支持 C++17 标准,并且链接文件系统库 (-lstdc++fs
)。具体的编译命令可能会有所不同,取决于你使用的编译器和平台。
内容由零声教学AI助手提供,问题来源于学员提问