使用 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/