skalibs

Mirror/fork of https://skarnet.org/software/skalibs/
git clone https://ccx.te2000.cz/git/skalibs
Log | Files | Refs | README | LICENSE

openreadfileclose.c (721B)


      1 /* ISC license. */
      2 
      3 #include <sys/stat.h>
      4 #include <errno.h>
      5 
      6 #include <skalibs/allreadwrite.h>
      7 #include <skalibs/stralloc.h>
      8 #include <skalibs/djbunix.h>
      9 
     10 int openreadfileclose (char const *file, stralloc *sa, size_t limit)
     11 {
     12   size_t n ;
     13   int e = errno ;
     14   int fd = openbc_read(file) ;
     15   if (fd < 0) return 0 ;
     16   {
     17     struct stat st ;
     18     if (fstat(fd, &st) < 0) goto err ;
     19     n = st.st_size ;
     20   }
     21   if (limit && (limit < n)) n = limit ;
     22   if (!stralloc_ready_tuned(sa, sa->len + n, 0, 0, 1)) goto err ;
     23   {
     24     size_t r ;
     25     errno = EPIPE ;
     26     r = allread(fd, sa->s + sa->len, n) ;
     27     sa->len += r ;
     28     if (r < n) goto err ;
     29   }
     30   fd_close(fd) ;
     31   errno = e ;
     32   return 1 ;
     33 
     34 err:
     35   fd_close(fd) ;
     36   return 0 ;
     37 }