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

How to determine the directory of the executable file using Qt?

本文关键字:可执行文件 何使用 Qt      更新时间:2023-10-16

我需要打开配置文件。配置文件位置是目录,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();

使用 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");