(TL;DR 在底部)
我会使用QFileInfo-class (docs) - 这正是它的用途:
QFileInfo 类提供独立于系统的文件信息。
QFileInfo 提供有关文件名和位置(路径)的信息
在文件系统中,它的访问权限以及它是目录还是
符号链接等文件的大小和最后修改/读取时间是
也提供。 QFileInfo 也可以用来获取关于
Qt 资源。
这是检查文件是否存在的源代码:
#include <QFileInfo>
(别忘了加上对应的#include-statement)
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())?
小心:exists()-function 的文档说:
如果文件存在则返回true;否则返回 false。
注意:如果文件是指向不存在文件的符号链接,则返回 false。
这并不准确。应该是:
如果路径(即文件或目录)存在则返回true;否则返回 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
(使用 exists 作为 Qt 5.2 中引入的 static;文档说静态函数更快,尽管我不确定在使用 isFile() 时仍然是这种情况方法;至少这是一个单行然后)
#include <QFileInfo>
// check if path exists and if yes: Is it a file and no directory?
bool fileExists = QFileInfo::exists(path) && QFileInfo(path).isFile();