aboutsummaryrefslogtreecommitdiff
path: root/libbb/xreadlink.c
diff options
context:
space:
mode:
Diffstat (limited to 'libbb/xreadlink.c')
-rw-r--r--libbb/xreadlink.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/libbb/xreadlink.c b/libbb/xreadlink.c
new file mode 100644
index 000000000..14863d9d5
--- /dev/null
+++ b/libbb/xreadlink.c
@@ -0,0 +1,38 @@
1/* vi: set sw=4 ts=4: */
2/*
3 * xreadlink.c - safe implementation of readlink.
4 * Returns a NULL on failure...
5 */
6
7#include <stdio.h>
8
9/*
10 * NOTE: This function returns a malloced char* that you will have to free
11 * yourself. You have been warned.
12 */
13
14#include <unistd.h>
15#include "libbb.h"
16
17char *xreadlink(const char *path)
18{
19 enum { GROWBY = 80 }; /* how large we will grow strings by */
20
21 char *buf = NULL;
22 int bufsize = 0, readsize = 0;
23
24 do {
25 buf = xrealloc(buf, bufsize += GROWBY);
26 readsize = readlink(path, buf, bufsize); /* 1st try */
27 if (readsize == -1) {
28 bb_perror_msg("%s", path);
29 free(buf);
30 return NULL;
31 }
32 }
33 while (bufsize < readsize + 1);
34
35 buf[readsize] = '\0';
36
37 return buf;
38}