#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>

#define BUFFSIZE (4096)
#define FILENAME "/tmp/bonk"

int main(int argc, char *argv[]) {
	FILE *fp;			/* output file */
	int c,				/* char read from stdin */
		count = 0;		/* number of chars read from stdin */

	if ((fp = fopen(FILENAME, "w")) == NULL) {
		err(EX_CANTCREAT, "Can't open %s for writing", FILENAME);
	}

	if (fprintf(fp, "Arguments were:\n") == 0) {
		err(EX_IOERR, "Couldn't write out argument header");
	}

	for (c = 1; c < argc; ++c) {
		if (fprintf(fp, "Arg %d: \"%s\"\n", c, argv[c]) == 0) {
			err(EX_IOERR, "Couldn't write out argument number %d", c);
		}
	}

	if (fprintf(fp, "\nRead from stdin:\n") == 0) {
		err(EX_IOERR, "Can't print stdin header");
	}

	while ((c = fgetc(stdin)) != EOF) {
		++count;
		if (fputc(c, fp) == EOF) {
			err(EX_IOERR, "Can't write character number %d. The character was %c (%d)", count, c, c);
		}
	}

	if (ferror(fp)) {
		err(EX_IOERR, "Can't read from stdin. Had read %d bytes so far", count);
	}

	if (fclose(fp) != 0) {
		err(EX_IOERR, "Can't close file %s", FILENAME);
	}

	return(0);
}
