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

新手上路,请多包涵

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

我当前的代码如下:

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

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

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

原文由 user1322915 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 503
1 个回答

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

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


如果您希望它返回 true 仅当 文件 存在和 false 如果路径存在但是一个文件夹,您可以将它与 QDir::exists() 结合使用:

 #include <QFileInfo>
#include <QDir>
QString path = "C:\\exampleFile.txt";
if(QFileInfo::exists(path) && !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
}

原文由 Donald Duck 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题