Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the directory of the executable file using Qt? [duplicate]

Tags:

c++

qt

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();
like image 380
Цунский Никита Avatar asked Feb 09 '17 11:02

Цунский Никита


People also ask

How do I find the path of a directory in QT?

A directory's path can be obtained with the path() function, and a new path set with the setPath() function. The absolute path to a directory is found by calling absolutePath(). The name of a directory is found using the dirName() function.

What is QFileInfo?

QFileInfo provides information about a file's name and position (path) in the file system, its access rights and whether it is a directory or symbolic link, etc. The file's size and last modified/read times are also available. QFileInfo can also be used to obtain information about a Qt resource.


1 Answers

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");
like image 110
jotik Avatar answered Oct 14 '22 13:10

jotik