如何在C ++中检查文件在Qt中是否存在 [英] How to check whether file exists in Qt in c++
问题描述
如何检查Qt中给定路径中是否存在文件?
How do I check whether a file exists in a given path or not in Qt?
我当前的代码如下:
QFile Fout("/Users/Hans/Desktop/result.txt");
if(!Fout.exists())
{
eh.handleError(8);
}
else
{
// ......
}
但是当我运行代码时,即使我在路径中提到的文件不存在,它也不会给出 handleError
中指定的错误消息.
But when I run the code it is not giving the error message specified in handleError
even though the file I mentioned in the path does not exist.
推荐答案
(位于底部的TL; DR)
我会使用 QFileInfo
类(文档)-这正是它的目的:
I would use the QFileInfo
-class (docs) - this is exactly what it is made for:
QFileInfo类提供与系统无关的文件信息.
The QFileInfo class provides system-independent file information.
QFileInfo提供有关文件名称和位置(路径)的信息在文件系统中,其访问权限以及它是目录还是目录符号链接等.文件的大小和上次修改/读取时间为也提供.QFileInfo也可以用于获取有关Qt资源.
QFileInfo provides information about a file's name and position (path) in the file system, its access rights and whether it is a directory or symbolic link, etc. The file's size and last modified/read times are also available. QFileInfo can also be used to obtain information about a Qt resource.
这是检查文件是否存在的源代码:
This is the source code to check whether a file exists:
#include <QFileInfo>
(不要忘记添加相应的 #include
语句)
bool fileExists(QString path) {
QFileInfo check_file(path);
// check if file exists and if yes: Is it really a file and no directory?
if (check_file.exists() && check_file.isFile()) {
return true;
} else {
return false;
}
}
还考虑:您是否只想检查路径是否存在( exists()
),还是要确保这是一个文件而不是目录( isFile()
)?
Also consider: Do you only want to check if the path exists (exists()
) or do you want to also make sure that this is a file and not a directory (isFile()
)?
要小心: exists()
-函数的文档说:
如果文件存在,则返回true;否则,返回true.否则返回false.
Returns true if the file exists; otherwise returns false.
注意:如果文件是指向不存在文件的符号链接,则返回false.
Note: If file is a symlink that points to a non-existing file, false is returned.
这不准确.应为:
如果路径(即文件或目录)存在,则返回true;否则,返回true.否则返回false.
Returns true if the path (i.e. file or directory) exists; otherwise returns false.
TL; DR
(具有上述功能的较短版本,节省了几行代码)
#include <QFileInfo>
bool fileExists(QString path) {
QFileInfo check_file(path);
// check if path exists and if yes: Is it really a file and no directory?
return check_file.exists() && check_file.isFile();
}
TL; Qt的DR> = 5.2
(使用Qt 5.2中引入的 exists
作为 static
;文档说static函数的速度更快,尽管我不确定这是同样也使用 isFile()
方法的情况;至少是单线的)
(using exists
as a static
which was introduce in Qt 5.2; the docs say the static function is faster, though I'm not sure this is still the case when also using the isFile()
method; at least this is a one-liner then)
#include <QFileInfo>
// check if path exists and if yes: Is it a file and no directory?
bool fileExists = QFileInfo::exists(path) && QFileInfo(path).isFile();
这篇关于如何在C ++中检查文件在Qt中是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!