在 Qt、C++ 中检查文件夹是否存在(并创建文件夹)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2241808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:40:30  来源:igfitidea点击:

Checking if a folder exists (and creating folders) in Qt, C++

c++qtfilesystems

提问by Switch

In Qt, how do I check if a given folder exists in the current directory?
If it doesn't exist, how do I then create an empty folder?

在Qt中,如何检查当前目录中是否存在给定文件夹?
如果它不存在,我该如何创建一个空文件夹?

回答by Kyle Lutz

To check if a directory named "Folder" exists use:

要检查名为“文件夹”的目录是否存在,请使用:

QDir("Folder").exists();

To create a new folder named "MyFolder" use:

要创建一个名为“MyFolder”的新文件夹,请使用:

QDir().mkdir("MyFolder");

回答by Petrucio

To both check if it exists and create if it doesn't, including intermediaries:

要检查它是否存在,如果不存在则创建,包括中介:

QDir dir("path/to/dir");
if (!dir.exists())
    dir.mkpath(".");

回答by Vitor Santos

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

当您使用 QDir.mkpath() 时,如果路径已存在,则返回 true,另一方面,如果路径已存在,则 QDir.mkdir() 返回 false。因此,根据您的程序,您必须选择更适合的程序。

You can see more on Qt Documentation

您可以在Qt 文档中查看更多信息

回答by Midhun

If you need an empty folder you can loop until you get an empty folder

如果你需要一个空文件夹,你可以循环直到你得到一个空文件夹

    QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    while(QDir(folder).exists())
    {
         folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    }
    QDir().mkdir(folder);

This case you will get a folder name with a number .

在这种情况下,您将获得一个带有数字的文件夹名称。

回答by matiasf

Why use anything else?

为什么要使用其他东西?

  mkdir(...);