File: openreadclose.c

package info (click to toggle)
dq 20230101-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,020 kB
  • sloc: ansic: 8,269; makefile: 363; sh: 176; python: 82
file content (41 lines) | stat: -rw-r--r-- 1,029 bytes parent folder | download | duplicates (5)
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
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "open.h"
#include "e.h"
#include "byte.h"
#include "openreadclose.h"

int openreadclose(const char *fn, stralloc *sa, long long bufsize) {

    int fd;
    long long r;
    struct stat st;

    if (bufsize <= 1) bufsize = 32;

    fd = open_read(fn);
    if (fd == -1) {
        if (errno == ENOENT) return 0;
        return -1;
    }
    if (fstat(fd, &st) == -1) { close(fd); return -1; }
    if (!stralloc_readyplus(sa, st.st_size)) { close(fd); return -1; }
    if (!stralloc_copys(sa, "")) { close(fd); return -1; }

    for (;;) {
        if (!stralloc_readyplus(sa, bufsize)) { close(fd); return -1; }
        r = read(fd, sa->s + sa->len, bufsize);
        if (r == 0) break;
        if (r == -1) {
            if (errno == EINTR) continue;
            if (errno == EAGAIN) continue;
            if (errno == EWOULDBLOCK) continue;
            close(fd);
            return -1;
        }
        sa->len += r;
    }
    close(fd);
    return 1;
}