summaryrefslogtreecommitdiff
path: root/src/libstddjb/sagetcwd.c
blob: d8c5dea7a5558a349bd28ee430f23b29583b7137 (plain)
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 <errno.h>
#include <skalibs/bytestr.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

int sagetcwd (stralloc *sa)
{
  unsigned int n = 128 ;
  int wasnull = !sa->s ;

  for (;;)
  {
    if (!stralloc_readyplus(sa, n)) goto err ;
    if (getcwd(sa->s + sa->len, n)) break ;
    if (errno != ERANGE) goto err ;
    n += 128 ;
  }
  sa->len += str_len(sa->s + sa->len) ;
  return 0 ;

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