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

use*_*915 71 c++ qt file-exists

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

我目前的代码如下:

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

if(!Fout.exists()) 
{       
  eh.handleError(8);
}  
else
{
  // ......
}
Run Code Online (Sandbox Code Playgroud)

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

moz*_*ozz 92

(TL; DR在底部)

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

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

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

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

#include <QFileInfo>
Run Code Online (Sandbox Code Playgroud)

(别忘了添加相应的#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

还要考虑:您是否只想检查路径是否存在(exists())还是要确保这是一个文件而不是目录(isFile())?

小心:exists()-function 的文档说:

如果文件存在,则返回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();
}
Run Code Online (Sandbox Code Playgroud)

TL; DR为Qt> = 5.2

(使用existsstatic这是在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();
Run Code Online (Sandbox Code Playgroud)

  • 只是一个建议,函数`bool fileExists(const QString&path)`中的代码可以进一步简化为:`return checkFile.exists()&& checkFile.isFile(); `@mozzbozz (4认同)

Don*_*uck 12

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

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

如果您希望它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
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*ony 8

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

试试这个:

qDebug() << "Function is being called.";
Run Code Online (Sandbox Code Playgroud)

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


Jer*_*fin 1

我会完全跳过使用 Qt 中的任何内容,而只使用旧标准access

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

  • @Styne666:我完全不确定 Qt 是否提供了任何东西来解决 setuid/setgid 程序的问题,这似乎是唯一重要的。他们争论“跨平台”的含义以及应该关心哪些标准,但如果我们只关心 Qt 支持的平台,那么这些大多都是没有意义的。 (2认同)