aboutsummaryrefslogtreecommitdiff
path: root/tools/add-header.c
blob: 75f74580f97b77466aa322767830f6ef5cfe0951 (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
64
65
66
67
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **const argv)
{
    int ret = EXIT_FAILURE;
    FILE *in = NULL, *out = NULL;

    if (argc < 3)
    {
        fprintf(stderr, "%s [arg ...] <in-file> <out-file>\n", *argv);
        goto end;
    }

    const char *const in_path = argv[argc - 2],
        *const out_path = argv[argc - 1];

    if (!(out = fopen(out_path, "wb")))
    {
        fprintf(stderr, "could not open %s: %s\n", out_path, strerror(errno));
        goto end;
    }
    else if (!(in = fopen(in_path, "rb")))
    {
        fprintf(stderr, "could not open %s: %s\n", in_path, strerror(errno));
        goto end;
    }

    for (int i = 1; i < argc - 2; i++)
    {
        if (fprintf(out, "%s", argv[i]) < 0
            || putc('\0', out) == EOF
            || ferror(out))
        {
            fprintf(stderr, "failed writing to %s\n", out_path);
            goto end;
        }
    }

    while (!feof(in))
    {
        char c;

        if ((!fread(&c, sizeof c, 1, in)
            || !fwrite(&c, sizeof c, 1, out))
            && (ferror(in) || ferror(out)))
        {
            fprintf(stderr, "ferror(%s)=%d, ferror(%s)=%d\n",
                in_path, ferror(in), out_path, ferror(out));
            goto end;
        }
    }

    ret = EXIT_SUCCESS;

end:
    if (out)
        fclose(out);

    if (in)
        fclose(in);

    return ret;
}