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

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

    Just my two cents, but doesn't the following code portably work in C++17?

    #include 
    #include 
    namespace fs = std::filesystem;
    
    int main(int argc, char* argv[])
    {
        std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
    }
    

    Seems to work for me on Linux at least.

    Based on the previous idea, I now have:

    std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");
    

    With implementation:

    fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
    {
        static auto exe_parent_path = fs::path(exe_path).parent_path();
        return exe_parent_path / filename;
    }
    

    And initialization trick in main():

    (void) prepend_exe_path("", argv[0]);
    

    Thanks @Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.

提交回复
热议问题