Qt中如何检查给定路径中是否存在文件?
我当前的代码如下:
QFile Fout("/Users/Hans/Desktop/result.txt");
if(!Fout.exists())
{
eh.handleError(8);
}
else
{
// ......
}
但是当我运行代码时,即使我在路径中提到的文件不存在,它也没有给出 handleError
中指定的错误消息。
(TL;底部的 DR)
我会使用 QFileInfo
-class (docs) - 这正是它的用途:
QFileInfo 类提供与系统无关的文件信息。 QFileInfo 提供有关文件名和文件系统中的位置(路径)、其访问权限以及它是目录还是符号链接等信息。文件的大小和最后修改/读取时间也可用。 QFileInfo 也可用于获取有关 Qt 资源的信息。
这是检查文件是否存在的源代码:
#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()
)?
小心:exists()
函数的文档说:
如果文件存在则返回真;否则返回假。注意:如果 file 是指向不存在文件的符号链接,则返回 false。
这并不精确。它应该是:
如果路径(即文件或目录)存在则返回true;否则返回假。
TL;博士
(上面函数的版本更短,省了几行代码)
#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 >=5.2 的 DR
(使用 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();
您可以使用 QFileInfo::exists()
方法:
#include <QFileInfo>
if(QFileInfo("C:\\exampleFile.txt").exists()){
//The file exists
}
else{
//The file doesn't exist
}
如果您希望它仅在 file 存在时返回 true
,如果路径存在但为文件夹则返回 false
,您可以将其与 QDir::exists()
组合:
#include <QFileInfo>
#include <QDir>
QString path = "C:\\exampleFile.txt";
if(QFileInfo(path).exists() && !QDir(path).exists()){
//The file exists and is not a folder
}
else{
//The file doesn't exist, either the path doesn't exist or is the path of a folder
}
true
,即使它“只是”一个文件。 OP 要求检查文件,而不是路径。
false
,则可以执行 QFileInfo(path).exists() && !QDir(path).exists()
。我已经编辑了我的答案以添加它。
您发布的代码是正确的。很可能还有其他问题。
试着把这个:
qDebug() << "Function is being called.";
在您的 handleError 函数内部。如果打印出上述消息,您就知道问题出在其他地方。
这就是我检查数据库是否存在的方式:
#include <QtSql>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QFileInfo>
QString db_path = "/home/serge/Projects/sqlite/users_admin.db";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(db_path);
if (QFileInfo::exists(db_path))
{
bool ok = db.open();
if(ok)
{
qDebug() << "Connected to the Database !";
db.close();
}
}
else
{
qDebug() << "Database doesn't exists !";
}
使用 SQLite
很难检查数据库是否存在,因为如果它不存在,它会自动创建一个新数据库。
我会跳过使用 Qt 中的任何内容,而只使用旧标准 access
:
if (0==access("/Users/Hans/Desktop/result.txt", 0))
// it exists
else
// it doesn't exist
access
——当然是 MS 和 gcc 端口。 Intel 使用支持它的 MS 库,Comeau 使用后端编译器的库。
bool fileExists(const QString &path)
中的代码可以进一步简化为:return checkFile.exists() && checkFile.isFile();
@mozzbozztrue
! (刚刚在我的系统上用 Qt 5.10 测试过)exists
函数(static
与否)将返回true
。但是问题是“我如何检查 file 是否存在”(而不是 directory)。看看链接的代码片段,我希望能解释我的意思。