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();
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With