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

狂风中的少年 提交于 2019-12-20 05:57:33

问题


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.getResources("Folder/test.txt"); The thing i want to do is, read and write a file. And it works fine. But im just wondering if you execute the program on a different pc it will not work. Because it dosnt detect the file.


    string path = "C:\\Users\\USER_EXAMPLE\\source\\repos\\Console\\Console\\Data.txt";
    inFile.open("C:\\Users\\USER_EXAMPLE\\source\\repos\\Console\\Console\\Data.txt");
    inFileWrite.open(path, ios_base::app);```

回答1:


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.



来源:https://stackoverflow.com/questions/57626409/how-can-i-access-resources-in-c-without-setting-the-full-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!