c++ - 如何实现readlink查找路径

标签 c++ linux path executable

使用 readlink 函数作为 How do I find the location of the executable in C? 的解决方案,我如何将路径放入 char 数组?另外,变量 buf 和 bufsize 代表什么以及如何初始化它们?

编辑:我正在尝试获取当前正在运行的程序的路径,就像上面链接的问题一样。该问题的答案是使用 readlink("proc/self/exe")。我不知道如何在我的程序中实现它。我试过了:

char buf[1024];  
string var = readlink("/proc/self/exe", buf, bufsize);  

这显然是不正确的。

最佳答案

这个 Use the readlink() function properly为了正确使用 readlink 函数。

如果你的路径在 std::string 中,你可以这样做:

#include <unistd.h>
#include <limits.h>

std::string do_readlink(std::string const& path) {
    char buff[PATH_MAX];
    ssize_t len = ::readlink(path.c_str(), buff, sizeof(buff)-1);
    if (len != -1) {
      buff[len] = '\0';
      return std::string(buff);
    }
    /* handle error condition */
}

如果你只追求固定路径:

std::string get_selfpath() {
    char buff[PATH_MAX];
    ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
    if (len != -1) {
      buff[len] = '\0';
      return std::string(buff);
    }
    /* handle error condition */
}

使用它:

int main()
{
  std::string selfpath = get_selfpath();
  std::cout << selfpath << std::endl;
  return 0;
}

关于c++ - 如何实现readlink查找路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525668/

相关文章:

linux - git pull 后,git pull 到 www 文件夹

linux - shell 中的浮点舍入

asp-classic - 在 ASP Classic 应用程序中获取根目录

c# - Nancy:是否有 Server.MapPath ("~/") 等价物?

c++ - 我需要分配一个具有 64 位值的变量

c++ - 一个类中的pthread

c++ - 括号是否会创建非推导上下文?

c++ - Portaudio + 作品 : Horrible sound quality

Linux文件权限和Java问题(权限保留)

ruby-on-rails - 无法在 Rails 中覆盖 Devise::RegistrationsController 吗?