/******* * ts.c * * Tiny timestamping filter for line-based output, written by * Jonas Anden . You may use it for whatever you * like as long as this header is retained. But don't blame * me if it breaks anything ;) * * // J * *******/ #define MAXLINELEN 1024 #include #include #include /* * Compile with: * gcc -Wall -o ts ts.c * * Sample use: * $ (for i in `seq 1 10`; do echo "Line $i"; sleep 1; done) | ./ts '%H:%m:%S [%%s] <- On a %A' * 21:03:23 [Line 1] <- On a Tuesday * 21:03:24 [Line 2] <- On a Tuesday * 21:03:25 [Line 3] <- On a Tuesday * 21:03:26 [Line 4] <- On a Tuesday * 21:03:27 [Line 5] <- On a Tuesday * 21:03:28 [Line 6] <- On a Tuesday * 21:03:29 [Line 7] <- On a Tuesday * 21:03:30 [Line 8] <- On a Tuesday * 21:03:31 [Line 9] <- On a Tuesday * 21:03:32 [Line 10] <- On a Tuesday * */ int main( int argc, char *argv[] ) { time_t t; struct tm *tmp; int buflen; char buf[MAXLINELEN], tbuf[MAXLINELEN]; if( argc != 2) { printf( "Usage:\n cat stream | %s | cat > timestamped-stream\nformat is a date(1) compatible time format with\na %%%%s where you want the input line. Example: %s \"%%H:%%m:%%S [%%%%s] <- On a %%A\"\n\nWARNING: Due to the inherent format string \"vulnerability\",\n DO NOT make this a setuid binary.\n", argv[0], argv[0] ); return 1; } while( !feof( stdin ) ) { if( fgets(buf, MAXLINELEN, stdin) == NULL ) break; buflen=strlen(buf); t = time(NULL); tmp = localtime(&t); if( strftime(tbuf, MAXLINELEN, argv[1], tmp) == 0 ) break; if( buf[buflen-1] == '\n' ) buf[buflen-1] = 0; printf( tbuf, buf ); putchar('\n'); fflush(stdout); } return 0; }