如果需要,如何从 Qt 中不存在的文件的文件名创建目录?

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

我希望我的应用程序在指定位置写入文件,因此在需要时创建适当的目录。 创建目录操作对我来说不是问题,但我需要目录路径。 我可以从文件路径中提取 if,但也许有 quick/concise/convenient 方法来完成完整操作?

我再说一遍,我不是在搜索基本的 makedir 函数,而是搜索一个可能不存在的文件的文件名,或者一个简单的 qt 函数来从文件路径字符串中提取 dir 路径字符串,所以我不必为这样的基本任务编写函数。

如果你有完整的文件路径,需要解压文件夹路径,可以这样做:

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

根据您确切的需要,您可能更愿意使用QFileInfo::canonicalPath()而不是absolutePath

或者,您也可以使用 QFileInfo::absoluteDir:

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

使用以下代码:

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

此代码将自动创建指定(不存在)文件的路径。


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

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