#include #include /* Read input from standard input and write to both standard output * and a file. * Supports only text files, and only short lines * -a append to file * -t prepend a timestamp */ void usage() { fprintf(stderr,"Usage: some_command | tee [-a] [-t] outfile\n"); exit (1); } int main(int argc, char *argv[]) { int a; FILE *fd = NULL; char *mode = "w"; char buf[1000]; char *timestamper = NULL; char tbuf[20]; struct tm *tm_p = NULL; time_t time_p = 0; if (argc <= 1) { usage(); } for (a = 1; (a < argc) && (argv[a][0] == '-'); a++) { /* check for append mode */ if (argv[a][1] == 'a') { mode = "a"; } if (argv[a][1] == 't') { timestamper = "%H:%M:%S "; } } if ((a >= argc) || !argv[a]) { usage(); } if ((fd = fopen(argv[a], mode)) == NULL) { perror(argv[a]); exit(2); } /* OK we should now have stdin to read from, stout and fd to write to */ while (fgets(buf,sizeof(buf),stdin)) { /* send a copy to both the file and to standard output */ fputs(buf,stdout); if (timestamper) { time_p = time(&time_p); tm_p = localtime(&time_p); if (tm_p) { strftime(tbuf, sizeof(tbuf), timestamper, tm_p); fputs(tbuf,fd); } } fputs(buf,fd); } /* no more, so close and exit */ fclose(fd); exit(0); }