How do I get the directory that a program is running from?

后端 未结 23 1652
温柔的废话
温柔的废话 2020-11-22 04:39

Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the

23条回答
  •  名媛妹妹
    2020-11-22 05:18

    I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:

    int main(int argc, char* argv[])
    {
        std::string argv_str(argv[0]);
        std::string base = argv_str.substr(0, argv_str.find_last_of("/"));
    }
    

    You can now just use this as a base for your relative path. So for example I have this directory structure:

    main
      ----> test
      ----> src
      ----> bin
    

    and I want to compile my source code to bin and write a log to test I can just add this line to my code.

    std::string pathToWrite = base + "/../test/test.log";
    

    I have tried this approach on Linux using full path, alias etc. and it works just fine.

    NOTE:

    If you are on windows you should use a '\' as the file separator not '/'. You will have to escape this too for example:

    std::string base = argv[0].substr(0, argv[0].find_last_of("\\"));
    

    I think this should work but haven't tested, so comment would be appreciated if it works or a fix if not.

提交回复
热议问题