160

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?

Donald Duck
  • 6,488
  • 18
  • 59
  • 79
Switch
  • 4,556
  • 11
  • 31
  • 38

5 Answers5

233

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

QDir("Folder").exists();

To create a new folder named "MyFolder" use:

QDir().mkdir("MyFolder");
Kyle Lutz
  • 7,592
  • 2
  • 18
  • 21
  • 1
    How 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
  • 1
    Why 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(".");
ManuelSchneid3r
  • 14,156
  • 9
  • 53
  • 94
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

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 .

Midhun
  • 3,450
  • 1
  • 20
  • 25
-11

Why use anything else?

  mkdir(...);
matiasf
  • 1,056
  • 1
  • 8
  • 16