summaryrefslogtreecommitdiffstats
path: root/combine.c
blob: 4629ca75e3986a51efb8117df5469a1cfb80d725 (plain)
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
// 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);
		}
	}
}