Linux C(++)获取可执行程序完整路径

代码


#include <sys/statfs.h>
#include <string>
#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/// get executable path
std::string get_cur_executable_path_()
{
    char *p                 = NULL;

    const int len           = 256;
    /// to keep the absolute path of executable's path
    char arr_tmp[len]       = {0};
    
    int n                   = readlink("/proc/self/exe", arr_tmp, len);
    if (NULL                != (p = strrchr(arr_tmp,'/')))
        *p = '\0';
    else
    {
        return std::string("");
    }

    return std::string(arr_tmp);
}
 
int main(int argc, char* argv[], char* env[])
{
    std::string exec_str    = get_cur_executable_path_();
    std::cout << "str=" << exec_str << "\n\n";
    return 0;

}

输出结果

posted @ 2021-03-28 21:24  mohist  阅读(2073)  评论(0编辑  收藏  举报