aboutsummaryrefslogtreecommitdiff
path: root/append.c
blob: 61b6ef6b9f58189a4ce391458de2dfb4ead22295 (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "weekly.h"

int append_stdin(const char *filename) {
    FILE *fp;
    size_t bufsz;
    char *buf;

    bufsz = BUFSIZ;
    buf = malloc(bufsz);
    if (!buf) {
        return -1;
    }

    fp = fopen(filename, "a");
    if (!fp) {
        perror(filename);
        free(buf);
        return -1;
    }

#if HAVE_WINDOWS
    while (fgets(buf, (int) bufsz, stdin) != NULL) {
        fprintf(fp, "%s", buf);
    }
#else
    while (getline(&buf, &bufsz, stdin) >= 0) {
        fprintf(fp, "%s", buf);
    }
#endif
    free(buf);
    fclose(fp);
    return 0;
}

int append_contents(const char *dest, const char *src) {
    char buf[BUFSIZ] = {0};
    FILE *fpi, *fpo;

    fpi = fopen(src, "rb+");
    if (!fpi) {
        perror(src);
        return -1;
    }

    fpo = fopen(dest, "ab+");
    if (!fpo) {
        perror(dest);
        fclose(fpi);
        return -1;
    }

    // Append source file to destination file
    while (fread(buf, sizeof(char), sizeof(buf), fpi) > 0) {
        fwrite(buf, sizeof(char), strlen(buf), fpo);
    }
    buf[0] = '\n';
    fwrite(buf, sizeof(char), 1, fpo);

    fclose(fpo);
    fclose(fpi);
    return 0;
}