summaryrefslogtreecommitdiffstats
path: root/combine.c
diff options
context:
space:
mode:
authorTomasz Kramkowski <tomasz@kramkow.ski>2024-11-12 13:36:10 +0000
committerTomasz Kramkowski <tomasz@kramkow.ski>2024-11-12 13:36:10 +0000
commit8d51757e02818146b05c805b81e167f118fca7dc (patch)
treeda5d2ae457f7255a403d9665a2777f6c225ba304 /combine.c
parent1fc39c620f2a9737851ef45ec77b2461ce1b7c30 (diff)
downloadcquine-master.tar.gz
cquine-master.tar.xz
cquine-master.zip
The quineHEADmaster
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);
+ }
+ }
+}