aboutsummaryrefslogtreecommitdiff
path: root/cfp.c
blob: 47b4bbee60c7d552786d8c3ad1b6a163c50a30a7 (plain) (blame)
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
#include "cat.h"

/* Function writes the contents of an opened file descriptor to stdout */
int cfp(FILE *fp, void *buf) {
    size_t br;

    /* Use the buffer to read the file in blocks, writing each block to stdout
     * as we go */
    while ((br = fread(buf, 1, BUFLEN, fp)) > 0) {
        if (fwrite(buf, 1, br, stdout) == 0) {
            perror(__FUNCTION__);
            return -1;
        }
    }

    /* If the last return value for br() was -1, there was an error; 0 is what
     * we expect */
    if (ferror(fp) != 0 || ferror(stdout) != 0) {
        perror(__FUNCTION__);
        return -1;
    }

    /* Force a write of any still-buffered data to stdout */
    if (fflush(stdout) != 0) {
        perror(__FUNCTION__);
        return -1;
    }

    /* Return success, since apparently nothing went wrong before we got here
     * */
    return 0;
}