#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;
}