10

I need to open Config file. Config file location is directory, where exe file is located. Basicly, how can I got this location?

I tried to use QDir, but my Current code returns error, when file isn't opened.

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();
jotik
  • 17,044
  • 13
  • 58
  • 123

1 Answers1

37

Use QCoreApplication::applicationDirPath() instead of QDir::currentPath().

QCoreApplication::applicationDirPath() returns a QString with the path of the directory that contains the application executable, whereas QDir::currentPath() returns a QString with the absolute path of the current directory of the current running process.

This "current directory" is generally not where the executable file resides but where it was executed from. Initially, it is set to the current directory of the process which executed the application. The current directory can also be changed during the lifetime of the application process and is mostly used to resolve relative paths at run time.

So in your code:

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

should open the same file as

QFile File("config.cfg");

But you probably just want

QFile File(QCoreApplication::applicationDirPath() + "/config.cfg");
jotik
  • 17,044
  • 13
  • 58
  • 123