使用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;
}
发布于 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;
}
发布于 2011-07-23 03:44:36
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;
}
}
https://stackoverflow.com/questions/5525668
复制相似问题