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();
    }
  • 相关阅读:
    LeetCode-034-在排序数组中查找元素的第一个和最后一个位置
    LeetCode-033-搜索旋转排序数组
    [leetcode]22. Generate Parentheses生成括号
    [leetcode]19. Remove Nth Node From End of List删除链表倒数第N个节点
    [leetcode]13. Roman to Integer罗马数字转整数
    [leetcode]12. Integer to Roman整数转罗马数字
    [leetcode]16. 3Sum Closest最接近的三数之和
    [leetcode]11. Container With Most Water存水最多的容器
    [leetcode]14. Longest Common Prefix 最长公共前缀
    [leetcode]9. Palindrome Number 回文数
  • 原文地址:https://www.cnblogs.com/chechen/p/15092316.html
Copyright © 2011-2022 走看看