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

后端 未结 5 665
深忆病人
深忆病人 2020-12-04 09:07

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?

相关标签:
5条回答
  • 2020-12-04 09:29

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

    QDir dir("path/to/dir");
    if (!dir.exists())
        dir.mkpath(".");
    
    0 讨论(0)
  • 2020-12-04 09:32

    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 .

    0 讨论(0)
  • 2020-12-04 09:33

    Why use anything else?

      mkdir(...);
    
    0 讨论(0)
  • 2020-12-04 09:37

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

    QDir("Folder").exists();
    

    To create a new folder named "MyFolder" use:

    QDir().mkdir("MyFolder");
    
    0 讨论(0)
  • 2020-12-04 09:48

    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

    0 讨论(0)
提交回复
热议问题