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?
Asked
Active
Viewed 1.4e+01k times
160
![](../../users/profiles/4284627.webp)
Donald Duck
- 6,488
- 18
- 59
- 79
![](../../users/profiles/205938.webp)
Switch
- 4,556
- 11
- 31
- 38
5 Answers
233
To check if a directory named "Folder" exists use:
QDir("Folder").exists();
To create a new folder named "MyFolder" use:
QDir().mkdir("MyFolder");
![](../../users/profiles/226814.webp)
Kyle Lutz
- 7,592
- 2
- 18
- 21
-
1How does this answer compare to @Petrucio's answer? I can't deduce this from the docs. – Jonas G. Drange Apr 27 '16 at 20:33
-
1Why it isn't static? `QDir::exists("absolutepath")` and `QDir::mkdir(""absolutepath")` – yalov Jun 19 '17 at 17:20
-
@yalov - because it would collide with non-static `QDir::mkdir("relative_path")`. Not possible to have both overloads. – Tomasz Gandor Oct 13 '17 at 21:51
-
7@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. – Petrucio Nov 17 '17 at 06:56
-
https://doc.qt.io/qt-5/qdir.html – KcFnMi Feb 12 '21 at 02:45
172
To both check if it exists and create if it doesn't, including intermediaries:
QDir dir("path/to/dir");
if (!dir.exists())
dir.mkpath(".");
![](../../users/profiles/978486.webp)
ManuelSchneid3r
- 14,156
- 9
- 53
- 94
![](../../users/profiles/828681.webp)
Petrucio
- 5,075
- 1
- 31
- 33
12
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
![](../../users/profiles/1622520.webp)
Vitor Santos
- 137
- 2
- 5
0
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 .
![](../../users/profiles/3239522.webp)
Midhun
- 3,450
- 1
- 20
- 25