如何使用Qt确定可执行文件的目录?

11

我需要打开配置文件。配置文件的位置在exe文件所在的目录中。基本上,我该如何获得这个位置?

我尝试使用QDir,但是当文件没有被打开时,我的代码会返回错误。

QString cfg_name = QDir::currentPath() + "config.cfg";
QFile File(cfg_name);
if (File.open(QIODevice::ReadOnly))
{
    QTextStream in(&File);
    int elementId;
    while (!in.atEnd())
    {
        QString line = in.readLine();
        filename[elementId] = line;
        elementId++;
    }
}
else
{
    QMessageBox msgBox;
    msgBox.setText("Can't open configuration file!");
    msgBox.exec();
}
File.close();
1个回答

41

使用QCoreApplication::applicationDirPath()代替QDir::currentPath()

QCoreApplication::applicationDirPath()返回一个包含应用程序可执行文件所在目录路径的QString,而QDir::currentPath()返回当前运行进程的绝对路径的QString

这个"当前目录"通常不是可执行文件所在的目录,而是它被执行的位置。最初,它被设置为执行应用程序的进程的当前目录。当前目录也可以在应用程序生命周期内更改,主要用于在运行时解决相对路径。

因此,在您的代码中:

QString cfg_name = QDir::currentPath() + "/config.cfg";
QFile File(cfg_name);

应该打开与相同文件

QFile File("config.cfg");

但是您可能只是想要

QFile File(QCoreApplication::applicationDirPath() + "/config.cfg");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接