QT开发中文网

std::ofstream outputFile(redfishEventLogFile, std::ios::app);改成检测这个文件存不存在 不存在就创建 存在就打开

你可以使用文件系统库 <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::filesystemexists() 函数检查指定的文件是否存在。如果文件不存在,则通过 std:ofstream 创建一个新的输出流,并写入一些内容;如果文件已经存在,则以附加模式(std:ios:app) 打开输出流,并追加内容。

请注意,在编译和运行代码之前,确保你的编译环境支持 C++17 标准,并且链接文件系统库 (-lstdc++fs)。具体的编译命令可能会有所不同,取决于你使用的编译器和平台。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=9322

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?