• Qt中常见的文件操作


    在Qt中,常用的文件操作类和函数主要包括:

    1. QFile类:用于操作文件,包括创建、打开、读取、写入和关闭文件等操作。

      • 示例:创建一个文件并写入内容

        QFile file("example.txt");
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream stream(&file);
            stream << "Hello, world!";
            file.close();
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
    2. QDir类:用于操作目录,包括创建、删除、遍历目录等操作。

      • 示例:遍历目录并打印文件名

        QDir directory("path/to/directory");
        QStringList fileList = directory.entryList(QDir::Files | QDir::NoDotAndDotDot);
        foreach (QString file, fileList)
        {
            qDebug() << file;
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
    3. QFileInfo类:用于获取文件信息,如文件大小、创建时间、修改时间等。

      • 示例:获取文件大小和修改时间

        QFileInfo fileInfo("example.txt");
        qDebug() << "File size: " << fileInfo.size();
        qDebug() << "Last modified: " << fileInfo.lastModified().toString();
        
        • 1
        • 2
        • 3
    4. QTextStream类:用于读写文本文件。

      • 示例:从文件中读取文本内容并打印

        QFile file("example.txt");
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream stream(&file);
            QString content = stream.readAll();
            qDebug() << content;
            file.close();
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
    5. QDataStream类:用于读写二进制文件。

      • 示例:写入和读取二进制数据

        QFile file("example.bin");
        if (file.open(QIODevice::WriteOnly))
        {
            QDataStream stream(&file);
            int value = 42;
            stream << value;
            file.close();
        }
        
        if (file.open(QIODevice::ReadOnly))
        {
            QDataStream stream(&file);
            int value;
            stream >> value;
            qDebug() << "Value: " << value;
            file.close();
        }
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17

    这些是Qt中常用的文件操作类和函数,可以根据具体需求选择适合的类和函数来进行文件操作。请注意,在使用这些类和函数之前,确保已经包含了相应的头文件,并且在.pro文件中添加了正确的模块依赖。

  • 相关阅读:
    Redission 使用Jackson处理LocalDateTime的一些坑
    SRS 流媒体服务器 Linux Dokcer
    应用联合、体系化推进。集团型化工企业数字化转型路径
    CI/CD --git版本控制系统
    Spring(二)-生命周期 + 自动装配(xml) +自动装配(注解)
    1、Pytorch初见
    敏捷开发使用
    【.NET Core】深入理解IO之Path
    The platform “win32“ is incompatible with this module.
    CSS 中背景background和img的区别和使用时机
  • 原文地址:https://blog.csdn.net/qq_40089560/article/details/134013402