如果需要,如何从Qt中不存在的文件的文件名创建dir
How to create dir if needed from filename of non-existing file in Qt?
我希望我的应用程序在指定的位置写一个文件,因此如果需要创建适当的目录。创建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
相关文章:
- CMake 生成的程序无法在 Windows 上链接:尝试链接到不存在的文件
- 在不存在的目录中打开文件,C 与 C++
- C++ Linux 可执行文件一直尝试使用不存在的库
- 从文本文件中读取时,即使不存在,也会找到额外的字符(例如"@")?
- 如果C 中不存在,如何创建文件夹
- 尝试使用 wxWidgets 从 zip 打开不存在的文件时无法捕获的异常
- 打开文件,如果不存在,则创建,确定是否创建
- ifstream不读取文件中存在的`0a`字节
- ifstream::is_open 返回 true,即使该位置不存在文件也是如此
- 复制文件时是否可以自动创建不存在的目录?
- 错误53:找不到文件,而是路径中存在所有DLL
- 打开不存在的文件时如何使流构造函数失败?
- 如果文件中不存在qt5中的文件,如何原子创建该文件
- C++仅当文件不存在时才打开文件进行写入
- 如果文件不存在,ifstream 会创建文件
- WinAPI - 如果文件不存在,则创建.ini文件
- QFileDialog:使用 getOpenFileName 允许不存在的文件
- QMediaPlaylist::addMedia() 对于不存在的文件返回 true
- 打开包含不存在文件的文件流后不会引发异常
- 在不存在文件损坏风险的情况下覆盖文件