如何在Qt中检查给定路径中是否存在文件?
我目前的代码如下:
QFile Fout("/Users/Hans/Desktop/result.txt");
if(!Fout.exists())
{
eh.handleError(8);
}
else
{
// ......
}
但是当我运行代码时,即使我在路径中提到的文件不存在,它也没有给出handleError
中指定的错误消息。
答案 0 :(得分:90)
(TL; DR在底部)
我会使用QFileInfo
- 类(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()
- 函数的文档说:
如果文件存在,则返回true;否则返回false。
注意:如果file是指向不存在文件的符号链接,则返回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
作为static
在Qt 5.2中引入;文档说静态函数更快,但我不确定在使用时仍然如此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();
答案 1 :(得分:11)
您可以使用QFileInfo::exists()
方法:
#include <QFileInfo>
if(QFileInfo("C:\\exampleFile.txt").exists()){
//The file exists
}
else{
//The file doesn't exist
}
如果您希望仅在文件存在时返回true
,并且false
如果路径存在但是文件夹,则可以将其与{{1}合并}:
QDir::exists()
答案 2 :(得分:8)
您发布的代码是正确的。有可能出现其他问题。
尝试这个:
qDebug() << "Function is being called.";
在handleError函数内部。如果打印上面的消息,你知道其他问题。
答案 3 :(得分:4)
我如何检查数据库是否存在:
#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
很难检查数据库是否存在,因为如果数据库不存在,它会自动创建一个新数据库。
答案 4 :(得分:1)
我会跳过使用Qt中的任何内容,只使用旧标准access
:
if (0==access("/Users/Hans/Desktop/result.txt", 0))
// it exists
else
// it doesn't exist