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.6e+01k times
        
    176
            
            
         
    
    
        Donald Duck
        
- 8,409
- 22
- 75
- 99
 
    
    
        Switch
        
- 5,126
- 12
- 34
- 40
4 Answers
248
            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,966
- 2
- 20
- 23
- 
                    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
- 
                    9@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
190
            
            
        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
        
- 15,850
- 12
- 65
- 103
 
    
    
        Petrucio
        
- 5,491
- 1
- 34
- 33
- 
                    
- 
                    1Because "." is the current dir, which we've set as the directory we want to create. – Petrucio Jun 03 '22 at 12:17
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
