summaryrefslogtreecommitdiff
path: root/src/libstddjb/sals.c
blob: 839df6dc49a1351dbaec4bb3bc120e5a8308a60f (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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* ISC license. */

#include <errno.h>
#include <string.h>

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

int sals (char const *fn, stralloc *sa, size_t *x)
{
  int n = 0 ;
  size_t sabase = sa->len ;
  size_t maxlen = 0 ;
  DIR *dir = opendir(fn) ;
  if (dir)
  {
    for (;;)
    {
      direntry *d ;
      size_t len ;
      errno = 0 ;
      d = readdir(dir) ;
      if (!d) break ;
      if (d->d_name[0] == '.')
        if (((d->d_name[1] == '.') && !d->d_name[2]) || !d->d_name[1])
          continue ;
      len = strlen(d->d_name) ;
      if (len > maxlen) maxlen = len ;
      if (!stralloc_catb(sa, d->d_name, len+1)) goto err ;
      n++ ;
    }
    if (errno) goto err ;
    dir_close(dir) ;
  }
  else if (errno != ENOENT) return -1 ;
  if (x) *x = maxlen ;
  return n ;

 err:
  dir_close(dir) ;
  sa->len = sabase ;
  return -1 ;
}