QT文件、文件夹的创建和检查

499 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天,点击查看活动详情

摘要

对于PC客户端编码的程序员来讲,将配置文件、图片、日志保存到指定的位置,可谓是经常会用到的功能。这里涉及到路径存在性检查、路径创建、文件存在性检查、文件创建四个部分的知识。本文将基于QT完成上述三个功能的阐释。

路径存在性检查

QDir提供了exist函数用于判断路径是否存在,使用方法有如下两种:

通过定义局部变量,判断路径是否存在
通过定义以路径为参数的QDir对象,判断路径是否存在。

    QString path = "d:/qt/qt/pracitce";
    QDir dir_1;
    if (!dir_1.exists(path))
    {
        qDebug()<<path<<" not exist";
    }

    QDir dir_2(path);
    if(dir_2.exists())
    {
        qDebug()<<path<<" exist";
    }

路径创建

路径创建QDir提供了两种方法,但是这两种方法差距还是很大的,如下:

通过mkdir逐级创建文件夹,父文件夹不存在时,返回错误,不创建,

//qt帮助文档的释义
bool QDir::mkdir(const QString &dirName) const
Creates a sub-directory called dirName.
Returns true on success; otherwise returns false.
If the directory already exists when this function is called, it will return false.

创建路径的示例代码

        QString qt_path = "d:/qt/qt/practice";
        auto path_list = qt_path.split("/");
        QString tmp_Path;
        for (auto path : path_list)
        {
            tmp_Path += path + "/";
            QDir dir(tmp_Path);
            if (!dir.exists())
            {
                dir.mkdir(tmp_Path);
            }
        }

通过mkpath直接创建到指定的文件夹,父文件夹不存在时,则创建父文件夹。

//qt帮助文档的释义
bool QDir::mkpath(const QString &dirPath) const
Creates the directory path dirPath.
The function will create all parent directories necessary to create the directory.
Returns true if successful; otherwise returns false.
If the path already exists when this function is called, it will return true.

创建路径的示例代码

    QString qt_path = "d:/qt/qt/practice";

    QDir dir(qt_path);
    if(!dir.exists())
    {
        dir.mkpath(qt_path);
    }

文件存在性检验和生成

文件的存在性检验和生成就简单的多了。QFile封装了相应的方法,

存在性检验 exists
生成 open,通过open参数的设定能够以不同的方式打开文件

[override virtual] bool QFile::open(QIODevice::OpenMode mode)
Reimplements: QIODevice::open(QIODevice::OpenMode mode).
Opens the file using OpenMode mode, returning true if successful; otherwise false.
The mode must be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. It may also have additional flags, such as QIODevice::Text and QIODevice::Unbuffered.
Note: In WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it.

创建文件的示例代码

   QString qt_path = "d:/qt/qt/practice/1.log";
   
   QFile file_1(qt_path);
   if(!file_1.exists())
   {
       file_1.open(QIODevice::ReadWrite);
   }