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

后端 未结 23 1673
温柔的废话
温柔的废话 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:13

    A library solution (although I know this was not asked for). If you happen to use Qt: QCoreApplication::applicationDirPath()

    0 讨论(0)
  • 2020-11-22 05:14

    Here's code to get the full path to the executing app:

    Windows:

    int bytes = GetModuleFileName(NULL, pBuf, len);
    return bytes ? bytes : -1;
    

    Linux:

    int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
    if(bytes >= 0)
        pBuf[bytes] = '\0';
    return bytes;
    
    0 讨论(0)
  • 2020-11-22 05:14

    For Win32 GetCurrentDirectory should do the trick.

    0 讨论(0)
  • 2020-11-22 05:17

    On Windows the simplest way is to use the _get_pgmptr function in stdlib.h to get a pointer to a string which represents the absolute path to the executable, including the executables name.

    char* path;
    _get_pgmptr(&path);
    printf(path); // Example output: C:/Projects/Hello/World.exe
    
    0 讨论(0)
  • 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.

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