如何在c++中检查Qt中是否存在文件

时间:2021-11-10 07:21:37

How do I check whether a file exists in a given path or not in Qt?

如何在Qt中检查给定路径中是​​否存在文件?

My current code is below:

我目前的代码如下:

QFile Fout("/Users/Hans/Desktop/result.txt");

if(!Fout.exists()) 
{       
  eh.handleError(8);
}  
else
{
  // ......
}

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.

但是当我运行代码时,即使我在路径中提到的文件不存在,它也没有给出handleError中指定的错误消息。

6 个解决方案

#1


72  

(TL;DR at the bottom)

(TL; DR底部)

I would use the QFileInfo-class (docs) - this is exactly what it is made for:

我会使用QFileInfo类(docs) - 这正是它的用途:

The QFileInfo class provides system-independent file information.

QFileInfo类提供与系统无关的文件信息。

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.

QFileInfo提供有关文件系统中文件名称和位置(路径)的信息,其访问权限以及是否是目录或符号链接等。文件的大小和上次修改/读取时间也可用。 QFileInfo还可用于获取有关Qt资源的信息。

This is the source code to check whether a file exists:

这是检查文件是否存在的源代码:

#include <QFileInfo>

(don't forget to add the corresponding #include-statement)

(别忘了添加相应的#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;
    }
}

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())还是要确保这是一个文件而不是目录(isFile())?

Be careful: The documentation of the exists()-function says:

注意:exists() - 函数的文档说:

Returns true if the file exists; otherwise returns false.

如果文件存在,则返回true;否则返回false。

Note: If file is a symlink that points to a non-existing file, false is returned.

注意:如果file是指向不存在文件的符号链接,则返回false。

This is not precise. It should be:

这不准确。它应该是:

Returns true if the path (i.e. file or directory) exists; otherwise returns false.

如果路径(即文件或目录)存在,则返回true;否则返回false。


TL;DR

TL; DR

(with shorter version of the function above, saving a few lines of code)

(使用上面函数的较短版本,保存几行代码)

#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;DR for Qt >=5.2

TL; DR为Qt> = 5.2

(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)

(使用作为静态引入,在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();

#2


8  

The code you've posted is correct. Chances are that something else is wrong.

您发布的代码是正确的。有可能出现其他问题。

Try putting this:

试试这个:

qDebug() << "Function is being called.";

inside of your handleError function. If the above message prints, you know something else is the problem.

在handleError函数内部。如果打印上面的消息,您知道其他问题。

#3


7  

You can use the QFileInfo::exists() method:

您可以使用QFileInfo :: exists()方法:

#include <QFileInfo>
if(QFileInfo("C:\\exampleFile.txt").exists()){
    //The file exists
}
else{
    //The file doesn't exist
}

If you want it to return true only if the file exists and false if the path exists but is a folder, you can combine it with QDir::exists():

如果您希望它仅在文件存在时返回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
}

#4


4  

That's how I check if the database exists:

这就是我检查数据库是否存在的方法:

#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 !";
}

With SQLite it's difficult to check if the database exists, because it automatically creates a new database if it doesn't exist.

使用SQLite很难检查数据库是否存在,因为如果数据库不存在,它会自动创建新数据库。

#5


1  

I would skip using anything from Qt at all, and just use the old standard access:

我会跳过使用Qt的任何东西,只使用旧的标准访问:

if (0==access("/Users/Hans/Desktop/result.txt", 0))
    // it exists
else
    // it doesn't exist

#6


0  

I think, it'll be useful too

我想,它也会有用

bool isFileExists(const std::string & filename){
  QFileInfo check_file(filename.c_str());
  return check_file.exists() && check_file.isFile();
}

#1


72  

(TL;DR at the bottom)

(TL; DR底部)

I would use the QFileInfo-class (docs) - this is exactly what it is made for:

我会使用QFileInfo类(docs) - 这正是它的用途:

The QFileInfo class provides system-independent file information.

QFileInfo类提供与系统无关的文件信息。

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.

QFileInfo提供有关文件系统中文件名称和位置(路径)的信息,其访问权限以及是否是目录或符号链接等。文件的大小和上次修改/读取时间也可用。 QFileInfo还可用于获取有关Qt资源的信息。

This is the source code to check whether a file exists:

这是检查文件是否存在的源代码:

#include <QFileInfo>

(don't forget to add the corresponding #include-statement)

(别忘了添加相应的#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;
    }
}

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())还是要确保这是一个文件而不是目录(isFile())?

Be careful: The documentation of the exists()-function says:

注意:exists() - 函数的文档说:

Returns true if the file exists; otherwise returns false.

如果文件存在,则返回true;否则返回false。

Note: If file is a symlink that points to a non-existing file, false is returned.

注意:如果file是指向不存在文件的符号链接,则返回false。

This is not precise. It should be:

这不准确。它应该是:

Returns true if the path (i.e. file or directory) exists; otherwise returns false.

如果路径(即文件或目录)存在,则返回true;否则返回false。


TL;DR

TL; DR

(with shorter version of the function above, saving a few lines of code)

(使用上面函数的较短版本,保存几行代码)

#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;DR for Qt >=5.2

TL; DR为Qt> = 5.2

(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)

(使用作为静态引入,在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();

#2


8  

The code you've posted is correct. Chances are that something else is wrong.

您发布的代码是正确的。有可能出现其他问题。

Try putting this:

试试这个:

qDebug() << "Function is being called.";

inside of your handleError function. If the above message prints, you know something else is the problem.

在handleError函数内部。如果打印上面的消息,您知道其他问题。

#3


7  

You can use the QFileInfo::exists() method:

您可以使用QFileInfo :: exists()方法:

#include <QFileInfo>
if(QFileInfo("C:\\exampleFile.txt").exists()){
    //The file exists
}
else{
    //The file doesn't exist
}

If you want it to return true only if the file exists and false if the path exists but is a folder, you can combine it with QDir::exists():

如果您希望它仅在文件存在时返回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
}

#4


4  

That's how I check if the database exists:

这就是我检查数据库是否存在的方法:

#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 !";
}

With SQLite it's difficult to check if the database exists, because it automatically creates a new database if it doesn't exist.

使用SQLite很难检查数据库是否存在,因为如果数据库不存在,它会自动创建新数据库。

#5


1  

I would skip using anything from Qt at all, and just use the old standard access:

我会跳过使用Qt的任何东西,只使用旧的标准访问:

if (0==access("/Users/Hans/Desktop/result.txt", 0))
    // it exists
else
    // it doesn't exist

#6


0  

I think, it'll be useful too

我想,它也会有用

bool isFileExists(const std::string & filename){
  QFileInfo check_file(filename.c_str());
  return check_file.exists() && check_file.isFile();
}