使用readlink函数作为How do I find the location of the executable in C?的解决方案,如何将路径放入字符数组?另外,变量buf和bufsize代表什么,我如何初始化它们?
编辑:我正在尝试获取当前运行的程序的路径,就像上面链接的问题一样。这个问题的答案是使用readlink("proc/self/exe")。我不知道如何在我的程序中实现它。我试过了:
char buf[1024];
string var = readlink("/proc/self/exe", buf, bufsize); 这显然是不正确的。
发布于 2011-04-03 04:38:18
此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;
}发布于 2016-07-13 21:30:24
公认的答案几乎是正确的,除非您不能依赖PATH_MAX,因为它是
如果系统没有这样的限制,则不保证为每个POSIX定义
。
(来自readlink(2)手册页)
此外,当它被定义时,它并不总是代表“真实”的限制。(参见http://insanecoding.blogspot.fr/2007/11/pathmax-simply-isnt.html )
readlink的手册页还提供了在symlink上执行此操作的方法:
使用静态大小缓冲区的
可能无法为符号链接内容提供足够的空间。缓冲区所需的大小可以从链路上调用lstat(2)返回的stat.st_size值中获得。但是,应该检查readlink()和read- linkat()写入的字节数,以确保符号链接的大小不会在两次调用之间增加。
但是,对于大多数/proc文件,在/proc/self/exe/的情况下,stat.st_size将为0。我看到的唯一解决方案是在不适合的时候调整buffer的大小。
为此,我建议使用vector<char>,方法如下:
std::string get_selfpath()
{
std::vector<char> buf(400);
ssize_t len;
do
{
buf.resize(buf.size() + 100);
len = ::readlink("/proc/self/exe", &(buf[0]), buf.size());
} while (buf.size() == len);
if (len > 0)
{
buf[len] = '\0';
return (std::string(&(buf[0])));
}
/* handle error */
return "";
}发布于 2011-04-03 06:02:08
让我们来看看the manpage是怎么说的:
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个字符的缓冲区:
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;
}https://stackoverflow.com/questions/5525668
复制相似问题