c++windowsresourcesconfigopenvr

How should I get the absolute path of a configuration file to be published alongside a windows .exe?


I'm making a windows application in C++. There's an API which requires a configuration file, and also the absolute path of that configuration file. ( https://github.com/ValveSoftware/openvr/wiki/Action-manifest ). I would have an easier time reasoning about this if I understood expected practices for publishing an executable.

Should I package MyApp.exe in a folder named MyApp, with MyApp.exe at the root, and all resources/config alongside it? Does that mean that, when run, all relative paths referenced from within the executable should be relative to the MyApp folder? How can I get the absolute path of the folder to which all relative paths are relative? (Whereby I could get the full absolute path of the config file by simply concatenating that absolute path with the relative path of the config file, which I should have control over...)

edit: to clarify, the API requires the filepath to be absolute. See the link: "The full path to the file must be provided; relative paths are not accepted." I'm not looking for c++ workarounds that would let me not need absolute filepaths: I need to find a way to get the absolute file path, because it is a constraint of the API.


Solution

  • Here's how you can do it on Windows.

    #include <Windows.h>
    #include <iostream>
    
    int main(){
        /*If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).*/
        HMODULE selfmodule = GetModuleHandleA(0);
    
        char absolutepath[MAX_PATH] = {0};
    
        uint32_t length = GetModuleFileNameA(selfmodule,absolutepath,sizoef(absolutepath));
    
        //lets assume our directory is C:/Users/Self/Documents/MyApp/MyApp.exe
        //let's backtrack to the /
        char* path = absolutepath+length;
        while(*path != '/'){
            *path = 0;
            --path;
        }
    
    
    
        //Now we are at C:/Users/Self/Documents/MyApp/
        //From here we can concat the Resources directory
    
        strcat(absolutepath,"Resources/somefile.txt");
    
        std::cout << absolutepath;
        //C:/Users/Self/Documents/MyApp/Resources/somefile.txt
    
        return 0;
    }