c++qtqtcoreqfileqcoreapplication

Qt: Telling a program to read other files from the same directory as it's placed in


I have a program which is going to take a few different files as input.
All I am going to know is that the files are going to be in the same folder as my program (and I know their names).

Is there a way to write a path to a file knowing only its name and that it will be in the same folder as the main program?


Solution

  • You are looking for these from QCoreApplication.

    QString QCoreApplication::applicationDirPath() [static]

    Returns the directory that contains the application executable.

    For example, if you have installed Qt in the C:\Qt directory, and you run the regexp example, this function will return "C:/Qt/examples/tools/regexp".

    On Mac OS X this will point to the directory actually containing the executable, which may be inside of an application bundle (if the application is bundled) Warning: On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

    and

    QString QCoreApplication::applicationFilePath() [static]

    Returns the file path of the application executable.

    For example, if you have installed Qt in the /usr/local/qt directory, and you run the regexp example, this function will return "/usr/local/qt/examples/tools/regexp/regexp".

    Warning: On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

    Depending on your exact use case, you use one of them, probably the former if you wish to get the executable path + your other files appended.