Mail merge by jonas

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void
die(char *msg) {
\x09fprintf(stderr, "%s\n", msg);
\x09exit(1);
}

#define TEMPLATE_MAXLEN 10100
char
templat[TEMPLATE_MAXLEN];

void
read_template(void) {
\x09int stop = 0;
\x09size_t pos = 0;
\x09while (!stop) {
\x09\x09if (
\x09\x09\x09TEMPLATE_MAXLEN - pos < 2 ||
\x09\x09\x09!fgets(templat + pos, TEMPLATE_MAXLEN - pos, stdin)
\x09\x09)
\x09\x09\x09die("error reading template");
\x09\x09if ('$' == templat[pos])
\x09\x09\x09stop = 1;
\x09\x09else
\x09\x09\x09pos += strlen(templat + pos);
\x09}
}

#define LINE_MAXLEN 4010
char
line[LINE_MAXLEN];

int
more_mail(void) {
\x09if (!fgets(line, LINE_MAXLEN, stdin))
\x09\x09die("error reading record head");
\x09if ('0' == line[0])
\x09\x09return 0;
\x09if ('1' == line[0])
\x09\x09return 1;
\x09die("error: record head has wrong format");
}

void
process_mail(void) {
\x09size_t pos;
\x09size_t len;
\x09for (pos = 0; '$' != templat[pos]; pos++) {
\x09\x09if ('@' == templat[pos]) {
\x09\x09\x09if ('i' != templat[++pos])
\x09\x09\x09\x09die("error: field marker has wrong format");
\x09\x09\x09if (!fgets(line, LINE_MAXLEN, stdin))
\x09\x09\x09\x09die("error reading record body");
\x09\x09\x09len = strlen(line);
\x09\x09\x09line[len - 1] = 0;
\x09\x09\x09fputs(line, stdout);
\x09\x09} else
\x09\x09\x09putchar(templat[pos]);
\x09}
}

int
main(void) {
\x09read_template();
\x09while (more_mail())
\x09\x09process_mail();
\x09return 0;
}

Note that non-ascii characters in the above source code will be escaped (such as \x9f).

download

return to the top page