How can i access resources in c++ without setting the full path

前端 未结 1 2018
囚心锁ツ
囚心锁ツ 2021-01-27 08:40

I wish to access my Resources in a programm but i dont want to use the full path which includes C:\\Users\\USER_EXAMPLE\\... In java there is an option to use getClass.getResour

相关标签:
1条回答
  • 2021-01-27 09:10

    In any case, if you want to access some resources, you will have to know the path.

    If you don't want to use absolute paths (which is something I understand for portability reasons), I think you can use kind of relative paths.

    To be more clear, simply using relative paths is bad because, as Some programmer dude commented in Eric's answer, the relative path is relative to the working directory. Consequently, if you launch the executable from another directory than its location directory, then the relative paths will be broken.

    But there is a solution:
    If you use the main() parameters, you can get the absolute path of the executable location.
    In fact, argv[0] contains the called command which is: absolute_path/executable_name. You just have to remove the executable name and you get the absolute path of the executable folder.
    You can now use paths relative to this one.

    It may look as follows:

    #include <string>
    
    int main(int argc, char ** argv)
    {
        // Get the command
        const std::string called_cmd = argv[0];
    
        // Locate the executable name
        size_t n = called_cmd.rfind("\\"); // Windows
        //size_t n = called_cmd.rfind("/"); // Linux, ...
    
        // Handle potential errors (should never happen but it is for robustness purposes)
        if(n == std::string::npos) // if pattern not found
            return -1;
    
        // Remove the executable name
        std::string executable_folder = called_cmd.substr(0, n);
    
        // ...
    
        return 0;
    }
    

    I think it will help you.


    EDIT:

    In fact, as already mentioned, argv[0] contains the called command. So to be rigorous, it is not necessarily the "absolute path" to the executable.
    Indeed, if the executable was called from a console/terminal with a relative path, this is what argv[0] will get.
    But in any case, the path resolution problem is resolved at call time, consequently it will always work if we use paths relative to the given argv[0] path.

    0 讨论(0)
提交回复
热议问题