• Qt 文件和文件夹操作


    资源:

    Qt 帮助文档
    Qt 5.9 c++开发指南 第七章

    复制文件

    bool QFile::copy(const QString &newName)
    [static] bool QFile::copy(const QString &fileName, const QString &newName)

    //设置工作目录
    bool ret1 = QDir::setCurrent("D:/2"); //true
    //将 D:/2/1.txt 复制到 D:/2 中更名为 2.txt
    bool ret2 = QFile::copy("1.txt", "2.txt"); //true
    bool ret3 = QFile::copy("1.txt", "1/2.txt"); //true 存在文件夹 1,1 中无 2.txt
    //如果新文件的路径不存在,则失败,不能创建路径
    bool ret4 = QFile::copy("1.txt", "1/11/1.txt"); //false 不存在 11 子文件夹
    //如果已有同名的文件,则失败,不能覆盖
    bool ret5 = QFile::copy("1.txt", "1/3.txt"); //false 1 子文件夹中存在 3.txt
    
    //创建文件,路径为相对路径,绝对路径为 D:/2/2.txt
    QFile file1("2.txt");
    //file1.setFileName("2.txt"); // 设置文件名称,路径为相对路径,和上面一样
    bool ret6 = file1.copy("2/2.txt"); //true 将 D:/2/2.txt 复制到 D:/2/2 文件夹,名字仍为 2.txt
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    设置文件的访问权限

    用户账户的介绍见 :

    Windows 10 技术与应用大全 宋翔

    使用函数:

    [static] bool QFile::setPermissions(const QString &fileName, QFileDevice::Permissions permissions)


    QFileDevice::Permissions

    QFile file("D:/2/2.txt");
    file.setPermissions(QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner);
    
    • 1
    • 2

    删除文件

    删除单个文件

    bool QFile::remove()
    [static] bool QFile::remove(const QString &fileName)
    bool QDir::remove(const QString &fileName)

    批量删除文件

    bool QDir::removeRecursively()

    示例

    bool ret1 = QDir::setCurrent("D:/2"); //true
    QFile file1("2.txt");
    //删除文件
    bool ret7 = file1.remove(); //true
    
    //1.txt 处于打开状态也删除,目录中无,但打开的文件还存在
    bool ret8 = QFile::remove("1.txt"); //true 
    
    QDir dir(QDir::current()); 
    bool ret9 = dir.remove("3.txt"); //true
    
    dir.setPath("1"); //相对路径  
    QString  strPath = dir.path(); // 相对路径为 1, 绝对路径为 D:/2/1
    
    // D:/2 的子文件夹 1 全部删除,包括里面所有的子目录和文件
    bool ret10 = dir.removeRecursively();  //true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    获取文件信息

    QFileInfo


    QFileInfo

    批量修改文件名

    例如一个文件夹中的文件格式为 : a_b_1.png,其中第三部分数字递增,现在需要批量修改该格式中的第二部分为 c ,示例代码如下:

    QString strPath("D:/1");
    QString strPathNew("D:/new");
    QDir dirNew;
    dirNew.mkpath(strPathNew);
    QString strSplit("_");
    
    //获取全部选中的文件
    QStringList strListFiles = QFileDialog::getOpenFileNames(this, "Select Files",
                                      strPath, "Images(*.png)");
    
    for (QString &strFile : strListFiles)
    {
        QFile file(strFile);
        QFileInfo fileInfo(file);
        QString strFileName(fileInfo.fileName()); //文件名
        QStringList strList = strFileName.split(strSplit);
        if (strList.size() < 3)
           continue;
    
        //查找文件格式为 a_b_num.png 的文件 num 为数字
        //最后一部分内容
        QString strLastPart = strList.at(2).split(".").first();
    
        //如果最后一部分只能是数字
        bool ok = false;
        strLastPart.toInt(&ok); //如果是纯十进制数字,则 ok = true
    
        //如果最后一部分格式为包含数字,也可以含其他字符
        //ok = strLastPart.contains(QRegExp("[0-9]"));
    
        //替换中间的字母
        if (strList.at(0) == "a" && strList.at(1) == "b" && ok)
        {
            strFileName.replace(str.indexOf("b"), 1, "c");
        }
    
        QFile::copy(strFile, strPathNew + "/" + strFileName);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    写文本文件

    void MyFile::writeFile(const QStringList &strListData)
    {
        QFile file("D:/LP/Test/data/samp1.txt");
        if (!file.open(QIODevice::ReadWrite | QIODevice::Text 
        							| QIODevice::Truncate))
        {
            return;
        }
    
        QTextStream dataStream(&file);
        dataStream << QString::fromLocal8Bit("***** 中文注释 *****")
        		   << "\n";
        dataStream << "a" << "b " << "c";
    
        file.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    读文本文件

    QFile file("D:/LP/Test/data/samp1.txt");
    if (!file.open(QIODevice::ReadOnly| QIODevice::Text)
    {
        return;
    }
    
    //读的文本中含中文
    QTextStream textStream(&file);
    textStream.setCodec("GBK");
    
    //跳过开头的空白行和含有 ** 的注释行
    while (!textStream.atEnd())
    {
       int pos = textStream.pos();
       QString strLine = textStream.readLine();
       if (strLine.simplified().isEmpty() || strLine.contains(QString("**"))
           continue;
    
       qDebug() << "pos: " << textStream.pos();
       qDebug() << "line 1: " << strLine ;
       break;
    }
    
    //回到起始位置 读取全部行
    textStream.seek(0);
    QStringList strList;
    
    while (!textStream2.atEnd())
    {
        strList << textStream.readLine();
    }
    
    file.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    压缩和解压缩文件

    How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

    压缩解压用到的脚本为 zipjs.bat
    压缩文件夹使用的方法:Using Shell.Application
    脚本调用语法:在命令行窗口定位到脚本所在的目录后,输入zipjs.bat,会有帮助文档说明。

    该脚本文件放在 D:/2 文件夹中。

    解压

    解压 .zip 文件:

    void readWriteFile::unzipFile()
    {
        QString strTemFile("D:\\2\\tem.bat"); //调用 zipjs.bat 的脚本
        QString strBatFile("D:\\2\\zipjs.bat");
        QString strSrcFilePath("D:\\2\\1.zip");
        QString strDesPath("D:\\2\\4");
        QFile file(strTemFile);
        if (file.open(QIODevice::ReadWrite | QIODevice::Text 
        					| QIODevice::Truncate))
        {
            QTextStream stream(&file);
            stream << "@echo off" << "\n"
                   << "call" << strBatFile << " unzip -source " 
                   << strSrcFilePath << " -destination " << strDesPath 
                   << " -keep yes -force yes" << "\n";
    
            file.close();
    
            QProcess process(NULL);
            process.setWorkingDirectory("D:/2");
            process.start(strTemFile);
            if (process.waitForFinished(1800000))
            {
                file.close();
                file.remove();
                qDebug() << "finished!";
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    压缩

    将文件夹压缩为.zip格式且不使用外部压缩工具。

    修改脚本执行命令:

    QString strSrcFilePath("D:\\2\\1");
    QString strDesPath("D:\\2\\4.zip");
    stream << "@echo off" << "\n"
           << "call" << strBatFile << " zipDirItem -source " 
           << strSrcFilePath << " -destination " << strDesPath 
           << " -keep yes -force yes" << "\n";
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    XML 文件读写

    Qt 读写 xml 文件

    注册表文件读写

    工程文件中加下面库:

    LIBS += User32.lib
    LIBS += Ole32.lib
    
    • 1
    • 2
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    void MainWindow::setKeyboard()
    {
        //找到默认输入法的 guid
        QSettings reg("HKEY_CURRENT_USER\\Software\\Microsoft\\CTF\\Assemblies\\0x00000804\\{34745C63-B2F0-4784-8B67-5E12C8701A31}",QSettings::NativeFormat);
        bool ok;
        QString strGuidProfiles = reg.value("Profile").toString();
        LANGID langid = QString("0x00000804").toUShort(&ok, 16); //2052
        REFGUID guidProfiles = QUuid(strGuidProfiles);
    
        //查找 CLSID
        QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\CTF\\SortOrder\\AssemblyItem\\0x00000804\\{34745C63-B2F0-4784-8B67-5E12C8701A31}",QSettings::NativeFormat);
        QStringList strListGroup = settings.childGroups();
        QString strRclsid("");
        for (QString &strGroup : strListGroup)
        {
            settings.beginGroup(strGroup);
            if (settings.value("Profile").toString() == strGuidProfiles)
            {
                strRclsid = settings.value("CLSID").toString();
                break;
            }
            settings.endGroup();
        }
        REFCLSID rclsid = QUuid(strRclsid);
    
        HRESULT hr;
        ITfInputProcessorProfiles *pProfiles;
    
        hr = CoCreateInstance(  CLSID_TF_InputProcessorProfiles,
                                NULL,
                                CLSCTX_INPROC_SERVER,
                                IID_ITfInputProcessorProfiles,
                                (LPVOID*)&pProfiles);
    
        if(SUCCEEDED(hr))
        {
            if (pProfiles->SetDefaultLanguageProfile(langid, rclsid, guidProfiles) != S_OK)
                qDebug("Failed to load default language profile.");
    
            if (pProfiles->ActivateLanguageProfile(rclsid, langid, guidProfiles) != S_OK)
                qDebug("Failed to active language profile.");
    
            pProfiles->Release();
        }
        //设置默认设置
        QSettings regSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\InputMethod\\Settings\\CHS",
        						QSettings::NativeFormat);
        regSettings.setValue("Default Mode", 0); //输入法默认模式(Default Mode)设置 中文(0) (英文为1)
        regSettings.setValue("Output CharSet", 0); //字符集 简体中文(0) (繁体为1)
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
  • 相关阅读:
    2流高手速成记(之九):基于SpringCloudGateway实现服务网关功能
    议程公布!Web3 建设者汇聚 DESTINATION MOON 分享见解与探讨
    python opencv环境配置 保姆级教程
    【React扩展】1、setState的两种写法、lazyLoad懒加载、Fragment标签和createContext()
    Python的基础语法(十五)
    梯度下降、损失函数、神经网络的训练过程
    WebRTC系列补充--native音量控制level
    数据结构从入门到实战——顺序表的应用
    git 报错Failed to connect to github.com port 443 after 21224 ms: Timed out 解决办法
    MFC Windows 程序设计[228]之拖拽列表(附源码)
  • 原文地址:https://blog.csdn.net/Lee567/article/details/126504036