summaryrefslogtreecommitdiff
path: root/src/libstddjb/openreadfileclose.c
blob: 90e6b477382052db4887360904ea551f7619c1ec (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
/* ISC license. */

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <skalibs/allreadwrite.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

int openreadfileclose (char const *file, stralloc *sa, unsigned int limit)
{
  unsigned int n ;
  int fd = open_readb(file) ;
  if (fd < 0) return 0 ;
  {
    struct stat st ;
    if (fstat(fd, &st) < 0) goto err ;
    n = st.st_size ;
  }
  if (limit && (limit < n)) n = limit ;
  if (!stralloc_ready_tuned(sa, sa->len + n, 0, 0, 1)) goto err ;
  {
    register unsigned int r = allread(fd, sa->s + sa->len, n) ;
    sa->len += r ;
    if (r < n) goto err ;
  }
  fd_close(fd) ;
  return 1 ;

err:
  {
    register int e = errno ;
    fd_close(fd) ;
    errno = e ;
  }
  return 0 ;
}