coreutils

General Software Utilities
git clone http://git.omkov.net/coreutils
Log | Tree | Refs | README | LICENCE | Download

coreutils/src/tee.c (75 lines, 1.9 KiB) -rw-r--r-- blame download

01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
// tee.c, version 1.0.3
// OMKOV coreutils implementation of POSIX tee
// Copyright (C) 2020, Jakob Wakeling
// MIT Licence

#include "util/error.h"
#include "util/optget.h"

#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#define VERSION "1.0.3"

static struct lop lops[] = {
	{ "help",    ARG_NUL, 256 },
	{ "version", ARG_NUL, 257 },
	{ NULL, 0, 0 }
};

static bool aflag;

static void hlp(void);
static void ver(void);

int main(int ac, char *av[]) { A0 = av[0];
	struct opt opt = OPTGET_INIT; opt.str = "ai"; opt.lops = lops;
	for (int o; (o = optget(&opt, av, 1)) != -1;) switch (o) {
	case 'a': { aflag = true; break; }
	case 'i': { signal(SIGINT, SIG_IGN); break; }
	case 256: { hlp(); return 0; }
	case 257: { ver(); return 0; }
	default: { return 1; }
	}
	
	setvbuf(stdout, NULL, _IONBF, 0);
	bool warned = false;
	
	FILE **files = (FILE **)malloc(sizeof (FILE) * (unsigned)(ac - opt.ind));
	if (!files) { error(1, "%s", serr()); }
	
	FILE **f = files;
	for (char **p = &av[opt.ind]; *p; ++p, ++f) {
		*f = fopen(*p, aflag ? "w" : "a");
		if (!*f) { warn("%s: %s", *p, serr()); --f; }
	} *f = NULL;
	
	char stdbuf[BUFSIZ * 16];
	for (size_t c; (c = fread(stdbuf, 1, sizeof (stdbuf), stdin)) != 0;) {
		for (f = files; *f; ++f) { fwrite(stdbuf, 1, c, *f); }
		fwrite(stdbuf, 1, c, stdout);
	}
	
	for (f = files; *f; ++f) { if (fclose(*f)) { warn("%s", serr()); }}
	
	free(files); return warned;
}

static void hlp(void) {
	puts("tee - duplicate standard input");
	puts("usage: tee [-ai] [file...]\n");
	puts("options:");
	puts("  -a         Append to files");
	puts("  -i         Ignore interrupt signals");
	puts("  --help     Display help information");
	puts("  --version  Display version information");
}

static void ver(void) {
	puts("OMKOV coreutils tee, version " VERSION);
	puts("Copyright (C) 2020, Jakob Wakeling");
	puts("MIT Licence (https://opensource.org/licenses/MIT)");
}