I want to store the path of the file the symbolic link is pointing to into bufff
. This works with my current implementation using readlink
but it grabs extra data I don’t need because my bufsize
is arbitrarily valued. I’m not sure how to size it according to the path of what the symbolic link points to because all I have is the path to the symbolic link. This is stored in path
which is a char array. How do I know to size bufff
with the size of the direct path string of the link if all I have is the path to the symbolic link?
char bufff[100]; size_t bufsize = 100; readlink(path,bufff,bufsize);
Advertisement
Answer
The readlink()
function returns the number of bytes copied to your buffer, without the final . This means that if you call
readlink()
with a buffer of 100 bytes and readlink()
returns 100, you need more space (even if the path was exactly 100 bytes, you would still need at least 1 byte to add a null character at the end).
The solution is to increase your buffer in a loop:
size_t bufsize = 255; /* Initial buffer size */ ssize_t result; char* buf = malloc(bufsize); /* Initial buffer allocation */ while ((result = readlink(path, buf, bufsize)) >= bufsize) { /* We double the buffer size, so next call should succeed ! */ bufsize *= 2; buf = realloc(buf, bufsize); } buf[result] = '';
WARNING: This is just an example, we don’t check if readlink
returns -1 in case of errors. Same for malloc
and realloc
. You should check errors in real-world.