首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何实现readlink查找路径

如何实现readlink查找路径
EN

Stack Overflow用户
提问于 2011-04-03 04:29:30
回答 4查看 41.2K关注 0票数 26

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

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

代码语言:javascript
复制
char buf[1024];  
string var = readlink("/proc/self/exe", buf, bufsize);  

这显然是不正确的。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-04-03 04:38:18

Use the readlink() function properly用于正确使用readlink函数。

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

代码语言:javascript
复制
#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 */
}

如果你只想要一条固定的路径:

代码语言:javascript
复制
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 */
}

要使用它:

代码语言:javascript
复制
int main()
{
  std::string selfpath = get_selfpath();
  std::cout << selfpath << std::endl;
  return 0;
}
票数 43
EN

Stack Overflow用户

发布于 2011-04-03 06:02:08

让我们来看看the manpage是怎么说的:

代码语言:javascript
复制
 readlink() places the contents of the symbolic link path in the buffer
 buf, which has size bufsiz.  readlink does not append a NUL character to
 buf.

好的。应该足够简单。给定1024个字符的缓冲区:

代码语言:javascript
复制
 char buf[1024];

 /* The manpage says it won't null terminate.  Let's zero the buffer. */
 memset(buf, 0, sizeof(buf));

 /* Note we use sizeof(buf)-1 since we may need an extra char for NUL. */
 if (readlink("/proc/self/exe", buf, sizeof(buf)-1) < 0)
 {
    /* There was an error...  Perhaps the path does not exist
     * or the buffer is not big enough.  errno has the details. */
    perror("readlink");
    return -1;
 }
票数 4
EN

Stack Overflow用户

发布于 2011-07-23 03:44:36

代码语言:javascript
复制
char *
readlink_malloc (const char *filename)
{
  int size = 100;
  char *buffer = NULL;

  while (1)
    {
      buffer = (char *) xrealloc (buffer, size);
      int nchars = readlink (filename, buffer, size);
      if (nchars < 0)
        {
          free (buffer);
          return NULL;
        }
      if (nchars < size)
        return buffer;
      size *= 2;
    }
}

摘自:http://www.delorie.com/gnu/docs/glibc/libc_279.html

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5525668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档