14

I have problem with the creation of dir with Qt. I would like to create a dir in documents'dir so, I make some things like that :

QString path("C:/Users/Me/Documents/MyApp/profiles/");
Qdir dir = QDir::root();
dir.mkdir(path);

But that doesn't work! I have test with "/" and "\" for the separators but in the two cases that not work.

How I can create my dir?

Thank you.

Ayberk Özgür
  • 4,986
  • 4
  • 38
  • 58
Guillaume
  • 8,741
  • 11
  • 49
  • 62

3 Answers3

39

You can do this:

QDir dir(path);
if (!dir.exists()){
  dir.mkdir(".");
}
yerlilbilgin
  • 3,041
  • 2
  • 26
  • 21
  • 9
    Preferably dir.mkpath(".") as stated here : https://stackoverflow.com/a/11517874/4706859 otherwise, if several folders have to be created, your call to dir.mkdir() will fail. Also note that there is no need for a test for directory existence unless you really intend to do something with its result. A test for the success of dir.mkpath(), on the other hand, may be useful. – SR_ Nov 03 '17 at 08:45
22

Instead of using dir.mkdir(), try to use QDir::mkpath;
i.e. as dir.mkpath(path);

Swapnil
  • 2,409
  • 4
  • 26
  • 48
Dcow
  • 1,413
  • 1
  • 19
  • 42
4

QDir dir = QDir::root() creates an instance of QDir configured to point to root and copies that setting to dir. To avoid the extra copy and code , you can use QDir dir(QDir::root);. On Windows it will point to the root of the system drive, usually C:\.

dir.mkdir(path); will attempt to create a subdirectory named path in the currently configured directory (root). This method expects a single directory name and not a full path. It also returns a bool result that you should be checking.

You probably want to be calling dir.mkpath(path) which will attempt to create the subdirectory specified along with all the necessary parent directories leading up to it. Again, you should check the result to see if it was successful.

Arnold Spence
  • 21,942
  • 7
  • 74
  • 67