spacm
spacm

Reputation: 300

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.

Upvotes: 4

Views: 2188

Answers (2)

kefir500
kefir500

Reputation: 4404

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.

Upvotes: 5

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

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

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 may prefer to use QFileInfo::canonicalPath() instead of absolutePath

Alternatively, you may also use QFileInfo::absoluteDir:

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

Upvotes: 0

Related Questions