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
(使用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();
Run Code Online (Sandbox Code Playgroud)
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)
您发布的代码是正确的.有可能出现其他问题.
试试这个:
qDebug() << "Function is being called.";
Run Code Online (Sandbox Code Playgroud)
在handleError函数内部.如果打印上面的消息,您知道其他问题.
我会完全跳过使用 Qt 中的任何内容,而只使用旧标准access:
if (0==access("/Users/Hans/Desktop/result.txt", 0))
// it exists
else
// it doesn't exist
Run Code Online (Sandbox Code Playgroud)