Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative path in QtCreator

I'm porting a console program with a config file containing lines of filename (relative to current directory) to Qt. When I run/debug the GUI in QtCreator, it seems cannot load the file from working directory.

Assuming my file system as follow:

C:/MyProjectSource
C:/MyProjectSource-Desktop-Debug // <-- created by QtCreator
C:/MyProjectSource-Desktop-Debug/debug/MyProgram.exe // <- my program
C:/MyProjectSource-Desktop-Debug/debug/params.txt    // <- program's config
C:/MyProjectSource-Desktop-Debug/debug/cfg/file1.txt // <- extra file
C:/MyProjectSource-Desktop-Debug/debug/cfg/file2.txt // <- extra file

params.txt looks like

# other setting    
...
cfg/file1.txt      # at this line, program crash, saying cannot open file
cfg/file2.txt
...
# other setting    

Code for reading file1.txt

std::ifstream ifs(filename); // <-- @runtime, filename = 'cfg/file1.txt'
if (!ifs)
{
    // failed inside QtCreator, but fine when start from explorer
    EMSG_OPENFILE(filename);
    exit(-1);
}

Baseline: no change to console program if possible. So, how to tell the QtCreator to understand the relative path? or should I enforce absolute path inside params.txt? Thanks.

Platform: QtCreator 2.6.1, Qt4.8, MinGW64, Win 7

like image 742
YamHon.CHAN Avatar asked Oct 22 '25 06:10

YamHon.CHAN


1 Answers

the relative path is relative to current working directory not to the directory in which the executable is stored, so you need to change the current working directory to the executable directory, just add this line after the main function:

QDir::setCurrent(QCoreApplication::applicationDirPath());

if you need to set the current working directory from Qt Creator: Project-> Run -> you will see Working Directory text box

enter image description here

then change this path to your executable location from browse button

like image 58
Wajdy Essam Avatar answered Oct 23 '25 20:10

Wajdy Essam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!