~mika/kethel2

ref: 0abf87c2f3a4ad952050e1b4ed248728d21ea971 kethel2/kethel2/mkpage.c -rw-r--r-- 2.3 KiB
0abf87c2 — mika feature: aggregate a month ago
                                                                                
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
68
69
70
71
72
73
74
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) {
    if (argc <= 2) {
        fprintf(stderr, "Usage: ./mkpage <input> <output>\n");
    }
    FILE* input  = fopen(argv[1], "rb");
    if (input == NULL) {
        fprintf(stderr, "mkpage: fopen: %s does not exist!\n", argv[1]);
        return -1;
    }
    FILE* output = fopen(argv[2], "w");
    if (output == NULL) {
        fprintf(stderr, "mkpage: fopen: could not open %s for writing\n", argv[2]);
        fclose(input);
        return -1;
    }

    uintptr_t lineno = 0;
    char buf[256]; // ! NOTE: lines longer than 255 chars do not process correctly

    while (fgets(buf, sizeof(buf), input) != NULL) {
        lineno++;

        if (strncmp("<!--", buf, 4) == 0) {
            const char* commandPtr = (buf + 4);
            if (strncmp(commandPtr, "LOAD", 4) == 0) {
                char path[256];
                if (sscanf((commandPtr + 4), "%s", path) == 0) {
                    fputs("ERROR: LOAD directive was improperly terminated!\n", stderr);
                    fprintf(stderr, "%s %lu | %s ", argv[1], lineno, buf);
                    fclose(input);
                    fclose(output);
                    return -1;
                }
                FILE* load = fopen(path, "r");
                if (load == NULL) {
                    fputs("ERROR: LOAD directive did not point to readable file!\n", stderr);
                    fprintf(stderr, "%s %lu | %s ", argv[1], lineno, buf);
                    fprintf(stderr, "From parsed path: %s", path);

                    fclose(input);
                    fclose(output);
                    return -1;
                }
                fseek(load, 0, SEEK_END);
                long file_size = ftell(load);
                fseek(load, 0, SEEK_SET);
                char* readBuf = malloc(file_size);
                size_t bytesRead = fread(readBuf, file_size, 1, load);
		if (bytesRead <= 0) {
			fputs("Failed to read from LOADed file\n", stderr);
			fclose(load);
			fclose(input);
			fclose(output);
			return -1;
		}
                fputs(readBuf, output);
                free(readBuf);
                fclose(load);
            }
        } else {
            fputs(buf, output);
        }
    }

    fclose(input);
    fclose(output);

    return 0;
}