1/* head.c - copy first lines from input to stdout. 2 * 3 * Copyright 2006 Timothy Elliott <tle@holymonkey.com> 4 * 5 * See http://opengroup.org/onlinepubs/9699919799/utilities/head.html 6 7USE_HEAD(NEWTOY(head, "?n#<0=10", TOYFLAG_USR|TOYFLAG_BIN)) 8 9config HEAD 10 bool "head" 11 default y 12 help 13 usage: head [-n number] [file...] 14 15 Copy first lines from files to stdout. If no files listed, copy from 16 stdin. Filename "-" is a synonym for stdin. 17 18 -n Number of lines to copy. 19*/ 20 21#define FOR_head 22#include "toys.h" 23 24GLOBALS( 25 long lines; 26 int file_no; 27) 28 29static void do_head(int fd, char *name) 30{ 31 int i, len, lines=TT.lines, size=sizeof(toybuf); 32 33 if (toys.optc > 1) { 34 // Print an extra newline for all but the first file 35 if (TT.file_no++) xprintf("\n"); 36 xprintf("==> %s <==\n", name); 37 xflush(); 38 } 39 40 while (lines) { 41 len = read(fd, toybuf, size); 42 if (len<0) perror_msg("%s",name); 43 if (len<1) break; 44 45 for(i=0; i<len;) if (toybuf[i++] == '\n' && !--lines) break; 46 47 xwrite(1, toybuf, i); 48 } 49} 50 51void head_main(void) 52{ 53 char *arg = *toys.optargs; 54 55 // handle old "-42" style arguments 56 if (arg && *arg == '-' && arg[1]) { 57 TT.lines = atolx(arg+1); 58 toys.optc--; 59 } else arg = 0; 60 loopfiles(toys.optargs+!!arg, do_head); 61} 62