Open file path



  • Hello,

    I want to read a text file in Qt. I guess it's kind of a stupid question but I didn't find the answer elsewhere on the forums.
    The problem is that if I just tell the name of the file ("Param.txt"), Qt does not find the file. I placed the file at different places to be sure (with the .pro, with the .exe) and even in the project Tree. However, in every case it did not find the file.

    The only way I can make it work is with the full path: "myfile("C:\TestQT\Face03\Param.txt");"
    However, this is not useful because I will want to release my program and the text file location should be relative to the .exe.

        std::ifstream myfile("Param.txt");
    
        if (myfile.is_open())
        {
            cout<<"worked";
        }
        else
        {
            cout<<"failed";
        }
    

    I also used QFiles instead of ifstream but the problem is the same,

    Thank you very much,

    Alex


  • Moderators

    Relative paths are relative to the working directory. Don't rely on it as it can differ depending on how your app is run (e.g. double click on exe or run from a command line or shortcut).

    To see what working directory is you can use QDir::currentPath. When run from the Qt Creator it's by default the build directory (one up from the executable), but it can be changed.

    If you want paths relative to the executable location you can get that using qApp->applicationDirPath():

    QString path = qApp->applicationDirPath() + "/Param.txt";
    

    Btw. Remember that backslash is an escape sequence character in c++ so if you use full path it should be C:\\TestQT\\Face03\\Param.txt. Prefer to use slashes in your paths instead. It's less error prone.



  • Perfect thank you, it works !

    Thanks,

    Alex


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.