zoukankan      html  css  js  c++  java
  • Qt 读写文件操作

    在项目开发过程中,有一个需求,程序启动时会定义一组全局变量,当用户操作这些变量,做一些修改,需要记住用户的操作,下次打开软件,按照用户上次设置的值进行计算显示。

    配置文件格式如下,非常简单

     

     在此解决思路是,先读取配置文件,循环每读一行,解析变量和它对应的值,全部存起来,然后用当前需要记录的值,去集合中找,如果找到了,就更新值,如果没找到就增加到集合中,最后全部再写入文件。

    #include <QtCore/QCoreApplication>
    #include <QFile>
    #include <QTextStream>
    #include <QDebug>
    
    
    void DumpCfg(const std::string& strName,const std::string& strValue)
    {
        QFile rfile("C:\Users\Administrator\Desktop\123.cfg");
    
        if (!rfile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qDebug() << "Can't open the file!" << endl;
        }
    
        std::map<std::string, std::string> mvars;
    
        while (!rfile.atEnd())
        {
            QByteArray line = rfile.readLine();//读一行
            QString strLine(line);
    
            if (strLine[0] == ';' || strLine.indexOf("--") !=-1)
            {
                continue;
            }
            
            int pos = strLine.indexOf("=");
    
            QString strVar = strLine.left(pos);
            QString strValue = strLine.right(strLine.length() - pos - 1);
            strValue = strValue.simplified();//返回一个字符串,该字符串已从开始和结束处删除空白,并将内部包括ASCII字符’	’,’
    ’,’v’,’f’,’
    ’和’ '.替换为‘ ’,如果替换后有两个空格的话,只保留一个空格。
        
            std::string sVar = strVar.toLocal8Bit();
            std::string sValue = strValue.toLocal8Bit();
    
            mvars[sVar] = sValue;
        }
        rfile.close();
    
        std::map<std::string, std::string>::iterator iter = mvars.find(strName);
    
        if (iter != mvars.end())
        {
            iter->second = strValue;
        }
        else
        {
            mvars[strName] = strValue;
        }
    
        //写文件
        QFile wfile("C:\Users\Administrator\Desktop\123.cfg");
    
        if (!wfile.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            qDebug() << "Can't open the file!" << endl;
        }
        QTextStream out(&wfile);
    
        for (std::map<std::string, std::string>::iterator iter = mvars.begin(); iter != mvars.end();++iter)
        {
            out << QString("%1=%2").arg(iter->first.c_str()).arg(iter->second.c_str()) << "
    ";
        }
    
        wfile.close();
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
    
        DumpCfg("abc", "10");//记录修改过得变量
    
        return a.exec();
    }
  • 相关阅读:
    Markdown高级使用之流程图
    Sentinel滑动窗口算法
    Markdown基础使用
    多线程学习(二)--整体简介
    MYSQL学习(三) --索引详解
    MYSQL学习(二) --MYSQL框架
    MYSQL 学习(一)--启蒙篇《MYSQL必知必会》
    数据结构学习(六) --排序
    数据结构学习(五)--查找
    数据结构学习(四)--图
  • 原文地址:https://www.cnblogs.com/chechen/p/15092316.html
Copyright © 2011-2022 走看看