Search code examples
c++qtpathdir

How to create dir if needed from filename of non-existing file in Qt?


I wish my app to write a file in a specified location, and therefore create the appropriate directory if needed. The create dir operation isn't a problem for me, but I need the dir path. I could extract if from the file path, but maybe is there a quick/concise/convenient way of doing the full operation?

I repeat, I'm not searching the basic makedir function, but one which would take the filename of a possibly non-existing file, or a simple qt function to extract the dir path string from the file path string, so I dont' have to write a func for such a basic task.


Solution

  • Use the following code:

    const QString filePath = "C:/foo/bar/file.ini";
    QDir().mkpath(QFileInfo(filePath).absolutePath());
    

    This code will automatically create the path to the specified (nonexistent) file.


    QFileInfo::absolutePath() extracts the absolute path to the specified file.

    QDir::mkpath() creates the previously extracted path.