如何使用Qt确定可执行文件的目录
How to determine the directory of the executable file using Qt?
我需要打开配置文件。配置文件位置是目录,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");
相关文章:
- 程序在使用 system() 启动另一个可执行文件时停止
- 如何更改使用 CPack 安装的可执行文件的名称?
- 在Linux上使用Clang / OLLVM交叉编译helloworld Windows可执行文件时的问题
- 如何在 linux 可执行文件中使用静态库
- 如何从命令行使用 cmake 为有根的安卓设备制作可执行文件?
- mingw32-make 使用"MinGW Makefiles"生成器跟踪 CMAKE 无法将可执行文件链接到对象库
- 使用 Premake5 构建项目不会生成可执行文件或中间体
- 如何使用 WINAPI 和 C++ 提取可执行文件的文件描述?
- 在使用PyInstaller冻结Python脚本时包含一个C++可执行文件
- 使用共享库编译可执行文件时仅链接所需的符号
- 如何将图像文件夹添加到CMake项目以便在c ++可执行文件中使用这些图像?
- 如何从控制台启动可执行文件并使用Qt读取输出
- 在可执行文件中使用带有符号链接的相对路径
- Codelite 问题 - 未指定可执行文件,使用"目标可执行文件"
- 在运行时在v110可执行文件中使用v90 COM dll是否安全
- 我的 c++ 可执行文件实际使用什么方法
- 为什么可执行文件在使用静态库编译后会增长如此之多
- 我如何在我的可执行文件中使用dll中的图像
- 试图与可执行文件一起使用gdb时出现问题
- 在同一个可执行文件中使用C/ c++进行不同的优化(plain、SSE、AVX)