summaryrefslogtreecommitdiffstats
path: root/combine.c
diff options
context:
space:
mode:
Diffstat (limited to 'combine.c')
-rw-r--r--combine.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/combine.c b/combine.c
new file mode 100644
index 0000000..4629ca7
--- /dev/null
+++ b/combine.c
@@ -0,0 +1,60 @@
+// SPDX-FileCopyrightText: 2024 Tomasz Kramkowski <tomasz@kramkow.ski>
+// SPDX-LicenseIdentifier: GPL-3.0-or-later
+
+// A tool to combine two files by replacing every instance of the character
+// sequence %s with the contents of the file named by the first argument.
+// This tool does not support escaping.
+
+#include <errno.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static const char *argv0 = "combine";
+
+void dump(FILE *f)
+{
+ if (fseek(f, 0, SEEK_SET) != 0) {
+ fprintf(stderr, "%s: error: Failed to rewind inclusion file: %s",
+ argv0, strerror(errno));
+ exit(EXIT_FAILURE);
+ }
+ int c;
+ while (c = fgetc(f), c != EOF) putchar(c);
+}
+
+int main(int argc, char **argv)
+{
+ if (argv[0] != NULL) argv0 = argv[0];
+ if (argc != 2) {
+ fprintf(stderr, "Usage: %s inclusion\n", argv0);
+ return EXIT_FAILURE;
+ }
+
+ FILE *inclusion = fopen(argv[1], "r");
+ if (inclusion == NULL) {
+ fprintf(stderr, "%s: error: Failed to open \"%s\": %s\n", argv0,
+ argv[1], strerror(errno));
+ return EXIT_FAILURE;
+ }
+
+ bool was_percent = false;
+ int c;
+ while (c = getchar(), c != EOF) {
+ if (was_percent) {
+ was_percent = false;
+ if (c == 's') {
+ dump(inclusion);
+ } else {
+ putchar('%');
+ putchar(c);
+ }
+ } else {
+ if (c == '%')
+ was_percent = true;
+ else
+ putchar(c);
+ }
+ }
+}