about summary refs log tree commit diff
path: root/src/libstddjb/sareadlink.c
blob: 90810e97def3cbf585747a6f0601d261f391b492 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* ISC license. */

#include <unistd.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

int sareadlink (stralloc *sa, char const *path)
{
  size_t n = 128 ;
  int wasnull = !sa->s ;
  ssize_t r ;

  for (;;)
  {
    if (!stralloc_readyplus(sa, n)) goto err ;
    r = readlink(path, sa->s + sa->len, n) ;
    if (r < 0) goto err ;
    if ((size_t)r < n) break ;
    n += 128 ;
  }
  sa->len += r ;
  return 0 ;

err:
  if (wasnull) stralloc_free(sa) ;
  return -1 ;
}