首页 > 编程语言 >【代码片段】Qt6.2.4 C++ 替换文件内容

【代码片段】Qt6.2.4 C++ 替换文件内容

时间:2022-09-24 16:55:45浏览次数:81  
标签:newFileContent Qt6.2 Apache24 文件 片段 C++ QString apacheHttpdConf append

参考

环境

环境 版本
windows 10
QT 6.2.4
Qt Creator 8.0.1 (Community)
qmake

注意

没找到修改指定行的方式。。。

本代码只适用于小文件的读取写入,大文件会导致内存不够。

代码

        QString apacheHttpdConfPath = file.filePath() + "/Apache24/conf/httpd.conf";
        // 读取旧文件内容
        QFile apacheHttpdConf(apacheHttpdConfPath);
        apacheHttpdConf.open(QIODevice::ReadOnly);
        QString newFileContent;
        while(!apacheHttpdConf.atEnd())
        {
            QByteArray row = apacheHttpdConf.readLine();
            QString s = row.data();
            // 判断修改的文件位置,并且防止重复写入,判断当前路径是否和配置文件内容一致,一致则不修改
            if(s.startsWith("Define SRVROOT") && !s.startsWith("Define SRVROOT \""+file.filePath()+"/Apache24\"")){
                newFileContent.append("# "+QString::fromLocal8Bit("配置目录修改,注释当前旧配置 ")+QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss:zzz") + "\r\n");
                newFileContent.append("# "+s);
                newFileContent.append("Define SRVROOT \""+file.filePath()+"/Apache24\" \r\n");
            }else{
                newFileContent.append(s);
            }
        }
        apacheHttpdConf.close();
        // 旧文件清空并将最新文件内容写入
        apacheHttpdConf.open(QIODevice::WriteOnly | QIODevice::Truncate);
        QTextStream apacheHttpdConfStream(&apacheHttpdConf);
        apacheHttpdConfStream << newFileContent;
        apacheHttpdConf.close();

标签:newFileContent,Qt6.2,Apache24,文件,片段,C++,QString,apacheHttpdConf,append
From: https://www.cnblogs.com/xiaqiuchu/p/16725956.html

相关文章