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

C++QtFilesystems

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

QDir("Folder").exists();

To create a new folder named "MyFolder" use:

QDir().mkdir("MyFolder");

Solution 2 - C++

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

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

Solution 3 - C++

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][1]

[1]: http://qt-project.org/doc/qt-4.8/qdir.html#mkpath "Qt Documentation"

Solution 4 - C++

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 .

Solution 5 - C++

Why use anything else?

  mkdir(...);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSwitchView Question on Stackoverflow
Solution 1 - C++Kyle LutzView Answer on Stackoverflow
Solution 2 - C++PetrucioView Answer on Stackoverflow
Solution 3 - C++Vitor SantosView Answer on Stackoverflow
Solution 4 - C++MidhunView Answer on Stackoverflow
Solution 5 - C++matiasfView Answer on Stackoverflow