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

后端 未结 23 1680
温柔的废话
温柔的废话 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条回答
  •  -上瘾入骨i
    2020-11-22 05:04

    Works with starting from C++11, using experimental filesystem, and C++14-C++17 as well using official filesystem.

    application.h:

    #pragma once
    
    //
    // https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
    //
    #ifdef __cpp_lib_filesystem
    #include 
    #else
    #include 
    
    namespace std {
        namespace filesystem = experimental::filesystem;
    }
    #endif
    
    std::filesystem::path getexepath();
    

    application.cpp:

    #include "application.h"
    #ifdef _WIN32
    #include     //GetModuleFileNameW
    #else
    #include 
    #include      //readlink
    #endif
    
    std::filesystem::path getexepath()
    {
    #ifdef _WIN32
        wchar_t path[MAX_PATH] = { 0 };
        GetModuleFileNameW(NULL, path, MAX_PATH);
        return path;
    #else
        char result[PATH_MAX];
        ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
        return std::string(result, (count > 0) ? count : 0);
    #endif
    }
    

提交回复
热议问题