问:如何在当前目录中打开文件?或者这有什么问题?

时间:2011-01-19 04:29:10

标签: c++ qt qt-creator qmake

我正在尝试在可执行文件的当前位置打开xml文件

        QString path = QDir::currentPath();
        path.append("/acc.xml");
        QFile file(path);

        if(!file.open(QIODevice::ReadOnly))
        {
            insertItem("IO ERR");
        }
  • 当我从Qt创建者运行时,一切正常。 currentPath()返回可执行文件夹的路径

  • 当我转到project-build-desktop/文件夹并尝试手动运行时currentPath()返回/home/user/Documents

修改

也尝试了相同的结果:

Qt::current().path();
Qt::current().absolutePath();

5 个答案:

答案 0 :(得分:9)

尝试使用QCoreApplication :: applicationDirPath()而不是QDir :: currentPath()。

有关详细信息,请参阅http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath

答案 1 :(得分:2)

检查QDir::currentPath()的返回值。我想当你从Qt Creator运行时,它会返回项目文件(* .pro)所在的路径。当你从外面跑步时,你会得到二进制文件的路径。

修改

我从未使用过Linux。但是,您可以尝试QDir

中的其他功能/组合
  • 的QDir ::电流()。路径()
  • 的QDir ::电流()。absolutePath()

答案 2 :(得分:2)

要在当前目录中打开文件,只需调用QFile构造函数

即可

我在我的Linux机器上测试了它并且它可以正常工作

#include <QtCore>

int main(int argc, char** argv){
    QFile some_file("test.xml");
    if(!some_file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << "Unable to open file";
    } else {
        qDebug() << "File open successfully";
    }
    exit(-1);
}

我运行./TestQFile,如果当前目录中有test.xml,它就可以运行。

更新:我注意到您的问题的措辞表明您希望该文件与可执行文件位于同一目录中,这可以按照以下方式完成:

// Getting directory of the executable
QFileInfo exec_fileinfo(argv[0]);
qDebug() << "Executable is in" << exec_fileinfo.absolutePath();

更新2:在QtCreator的项目面板下,有一个工作目录字段。如果您通过QtCreator运行它,那么这是QDir :: currentPath()返回的目录。

答案 3 :(得分:1)

我在搜索类似的解决方案时发现了这个问题。我认为打开具有固定名称(没有对话框和用户参与)的外部文件的最便携方式是使用Resource System

在我的情况下,我创建了一个前缀为/config的新资源文件,并添加了文件(称为settings.xml)。在代码中,我根本不需要使用任何路径函数。我改用资源系统。因此像QFile file(":/config/settings.xml")这样的调用工作正常。在Windows上使用QT creator 2.0.1和QT 4.7。

答案 4 :(得分:0)

我的提示是:文件名 + 文件的绝对路径,然后再打开它。为此,我在 applicationDirPath 对象(在我的例子中为 QCoreApplication 对象)上调用方法 a,它返回应用程序可执行文件的路径。无需遍历 argv 数组。就是这样并且有效

 int main(int argc, char *argv[]) {
   QCoreApplication a(argc, argv);
   const QString fileName = "someJsonFile.JSON";
   const QString currentExecDir = a.applicationDirPath();
   QFile myFile(currentExecDir + '/' + fileName);
   if (myFile.open(QIODevice::ReadOnly)) {
    qDebug()<< "The file "<< fileName<< " has been opened successfully";
   }
   else {
     qDebug()<< "Failed to open file "<< fileName<< " in "<< currentExecDir;
   }
   return a.exec();
}

注意 有关 applicationDirPath 方法的信息,请参阅 Qt 文档,因为它假定应用程序未更改当前目录