ChatGPT解决这个技术问题 Extra ChatGPT

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

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?


K
Kyle Lutz

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

QDir("Folder").exists();

To create a new folder named "MyFolder" use:

QDir().mkdir("MyFolder");

How does this answer compare to @Petrucio's answer? I can't deduce this from the docs.
Why it isn't static? QDir::exists("absolutepath") and QDir::mkdir(""absolutepath")
@yalov - because it would collide with non-static QDir::mkdir("relative_path"). Not possible to have both overloads.
@JonasG.Drange This answer does not create intermediate folders in a complex/path/structure/with/intermediate/folders. My answer is objectively better; the reason it has less upvotes is because it was posted two years after this one.
M
ManuelSchneid3r

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

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

Why pass the "." argument in dir.mkpath(".")?
Because "." is the current dir, which we've set as the directory we want to create.
V
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.

You can see more on Qt Documentation


m
matiasf

Why use anything else?

  mkdir(...);

Because you can't use it like that in Qt.