summaryrefslogtreecommitdiff
path: root/src/readclose.c
blob: 2804965d215f4b79f04102b7e87e9a12e1aa3b99 (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
45
46
47
48
49
50
51
52
53
54
55
#include "readclose.h"

#include <unistd.h>

#include "error.h"
#include "open.h"

/**
	@file readclose.c
	@author kp
	@source qlibs
	@brief This is the successor of the older 'slurpclose.c' file. The function
   'slurpclose'  is now called  'readclose_append'.  The other function
   'readclose' was introduced here initial.
*/

int readclose_append(int fd, stralloc *sa, unsigned int bufsize)
{
  int r;
  for (;;) {
    if (!stralloc_readyplus(sa, bufsize)) {
      close(fd);
      return -1;
    }
    r = read(fd, sa->s + sa->len, bufsize);
    if (r == -1)
      if (errno == EINTR) continue;
    if (r <= 0) {
      close(fd);
      return r;
    }
    sa->len += r;
  }
}

int readclose(int fd, stralloc *sa, unsigned int bufsize)
{
  if (!stralloc_copys(sa, "")) {
    close(fd);
    return -1;
  }
  return readclose_append(fd, sa, bufsize);
}

int openreadclose(const char *fn, stralloc *sa, unsigned int bufsize)
{
  int fd;
  fd = open_read((char *)fn);
  if (fd == -1) {
    if (errno == ENOENT) return 0;
    return -1;
  }
  if (readclose(fd, sa, bufsize) == -1) return -1;
  return 1;
}