我需要打开配置文件。配置文件的位置是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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句