/* Truncate input, keeping only the first few lines. Usage: ./head {line_count} < input.txt > output.txt Where {line_count} is the number of lines. Sign is ignored, so "-10" is interpreted the same as "10". This tool basically implements a subset of the standard head(1) tool, except we optimize for code size. */ #include #include #define USE_BUFFERED_INPUT int main(int argc, char **argv) { int line_count, current_line = 1; int i; #ifdef USE_BUFFERED_INPUT int capacity = 0, size = 0, eof = 0; char *buffer = NULL; #endif if( argc != 2 ) return printf("%s {line_count}\n", *argv); line_count = abs(atoi(argv[1])); #ifdef USE_BUFFERED_INPUT while( !eof ) { /* Extend input buffer. */ if( size == capacity ) { capacity = (capacity != 0 ? capacity * 2 : 256); if( (buffer = (char*)realloc(buffer, capacity)) == NULL ) { fprintf(stderr, "Out of memory (need %d)\n", capacity); return 1; } } size = fread(buffer, 1, capacity, stdin); eof = size < capacity; if( current_line <= line_count ) { for(i = 0; i < size; i++) { if( buffer[i] == '\n' ) { current_line++; if( current_line > line_count ) { size = i + 1; break; } } } fwrite(buffer, size, 1, stdout); size = 0; } } if( current_line <= line_count ) fwrite(buffer, size, 1, stdout); free(buffer); #else while( (i = getchar()) != EOF ) { if( current_line <= line_count ) putchar(i); if( i == '\n' ) current_line++; } #endif return 0; }