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

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

本文关键字:不存在 文件 文件名 dir 创建 Qt 如果      更新时间:2023-10-16

我希望我的应用程序在指定的位置写一个文件,因此如果需要创建适当的目录。创建dir操作对我来说不是问题,但我需要dir路径。我可以从文件路径中提取,但也许有一个快速/简洁/方便的方法来做完整的操作?

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

使用以下代码:

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

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


QFileInfo::absolutePath()提取指定文件的绝对路径。

QDir::mkpath()创建前面提取的路径。

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

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