如何实现readlink来查找路径

如何实现readlink来查找路径

本文介绍了如何实现readlink来查找路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用readlink函数作为,我如何得到一个char数组的路径?此外,变量buf和bufsize代表什么,如何初始化它们?

Using the readlink function used as a solution to how to find the location of the executable in C, how would I get the path into a char array? Also, what do the variables buf and bufsize represent and how do I initialize them?

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

I am trying to get the path of the currently running program, just like the question linked above. The answer to that question said to use readlink("proc/self/exe"). I do not know how to implement that into my program. I tried:

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

这显然是不正确的。

推荐答案

此正确使用 readlink 函数。

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

If you have your path in a std::string, you could do something like this:

#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 */
}

如果你只是在一个固定的路径后:

If you're only after a fixed path:

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;
}

这篇关于如何实现readlink来查找路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:41