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

Цун*_*ита 3 c++ qt

我需要打开Config文件.配置文件位置是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();
Run Code Online (Sandbox Code Playgroud)

jot*_*tik 14

QCoreApplication::applicationDirPath()而不是QDir::currentPath().

QCoreApplication::applicationDirPath()返回QString包含应用程序可执行文件的目录路径,然后QDir::currentPath()返回QString带有应用程序当前目录的绝对路径的a .

"当前目录"通常不是可执行文件所在的位置,而是执行文件的位置.当前目录也可以在应用程序进程的生命周期内更改,并用于在运行时解析相对路径.

所以在你的代码中:

QString cfg_name = QDir::currentPath() + "/config.cfg";
QFile File(cfg_name);
Run Code Online (Sandbox Code Playgroud)

应该打开相同的文件

QFile File("config.cfg");
Run Code Online (Sandbox Code Playgroud)

但你可能只是想要

QFile File(QCoreApplication::applicationDirPath() + "/config.cfg");
Run Code Online (Sandbox Code Playgroud)