How can I create a dir, if necessary, from the filename of a non-existent file in Qt?

I want my application to write the file to the specified location and hence create the appropriate directory. The create dir operation is not a problem for me, but I need the dir path. I could extract if the path is from the file, but maybe there is a quick / shortest / convenient way to do the full operation?

Again, I'm not looking for a basic makedir function, but one that would take the filename of a non-existent file, or just a qt function to extract the dir path string from the file path string, so I don't need to write func for such a basic task.

+3


source to share


2 answers


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 (non-existent) file.




QFileInfo::absolutePath()

Retrieves the absolute path to the specified file.

QDir::mkpath()

creates a previously extracted path.

+4


source


If you have the full path to the file and need to extract the path to the folder, you can do it like this:

QFile file(full_path_to_the_file);
QFileInfo info(file);
QString directoryPath = info.absolutePath();
//now you can check if the dir exists:
if(QDir(directoryPath).exists())
    //do stuff

      

Depending on what exactly you need, you can use QFileInfo::canonicalPath()

insteadabsolutePath



Alternatively, you can also use QFileInfo::absoluteDir

:

QFile file(full_path_to_the_file);
QFileInfo info(file);
if(info.absoluteDir().exists())
    //do stuff

      

0


source







All Articles