Qt QFileInfo.isDir()返回错误结果

Qt QFileInfo.isDir() returns wrong result

本文关键字:返回 错误 结果 QFileInfo isDir Qt      更新时间:2023-10-16

我有Qt类QFileInfo的问题这里是一些代码的例子

 QString path = "C:\Some\Path";
 QFileInfo pathFileInfo(path);
 if (pathFileInfo.isDir()){
     qDebug() << "path is dir, cdUp";
     pathDir.cdUp();
  } else {
      qDebug() << "path is not dir, getting dir";
      pathDir = pathFileInfo.dir();
  }

当文件夹"Some"中存在dir路径时,pathFileInfo.isDir()返回false
如果我正确的路径并添加一个QDir::separator()到它pathFileInfo.isDir()返回true
如何正确使用此方法来检测是否给定的路径是文件夹或文件?

小心使用反斜杠,它们必须被转义。替换路径声明:

QString path = "C:\Some\Path";

或使用:

QString path = "C:/Some/Path";

"/"""这样的斜杠在Linux和Windows中是不同的。您可以使用static方法QString QDir::toNativeSeparators ( const QString & pathName )来获得具有正确分隔符的正确路径。

那么就这样做:

QString path = QDir::toNativeSeperators( "/your/path/here" );
//you can also use path2 instead of path since they are both the same
QString path2 = QDir::toNativeSeperators( "/yourpath/here" );
 QFileInfo pathFileInfo(path);
 if (pathFileInfo.isDir()){
     qDebug() << "path is dir, cdUp";
     pathDir.cdUp();
  } else {
      qDebug() << "path is not dir, getting dir";
      pathDir = pathFileInfo.dir();
  }

这是文档的链接