xref: /original-bsd/usr.bin/head/head.c (revision 1a56dd2c)
1 /*
2  * Copyright (c) 1980, 1987 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #ifndef lint
14 char copyright[] =
15 "@(#) Copyright (c) 1980, 1987 Regents of the University of California.\n\
16  All rights reserved.\n";
17 #endif /* not lint */
18 
19 #ifndef lint
20 static char sccsid[] = "@(#)head.c	5.3 (Berkeley) 04/19/88";
21 #endif /* not lint */
22 
23 #include <stdio.h>
24 #include <ctype.h>
25 /*
26  * head - give the first few lines of a stream or of each of a set of files
27  *
28  * Bill Joy UCB August 24, 1977
29  */
30 
31 main(argc, argv)
32 	int	argc;
33 	char	**argv;
34 {
35 	register int	ch, cnt;
36 	int	firsttime, linecnt = 10;
37 
38 	if (argc > 1 && argv[1][0] == '-') {
39 		if (!isdigit(argv[1][1])) {
40 			fprintf(stderr, "head: illegal option -- %c\n", argv[1][1]);
41 			goto usage;
42 		}
43 		if ((linecnt = atoi(argv[1] + 1)) < 0) {
44 usage:			fputs("usage: head [-line_count] [file ...]\n", stderr);
45 			exit(1);
46 		}
47 		--argc; ++argv;
48 	}
49 	/* setlinebuf(stdout); */
50 	for (firsttime = 1, --argc, ++argv;; firsttime = 0) {
51 		if (!*argv) {
52 			if (!firsttime)
53 				exit(0);
54 		}
55 		else {
56 			if (!freopen(*argv, "r", stdin)) {
57 				fprintf(stderr, "head: can't read %s.\n", *argv);
58 				exit(1);
59 			}
60 			if (argc > 1) {
61 				if (!firsttime)
62 					putchar('\n');
63 				printf("==> %s <==\n", *argv);
64 			}
65 			++argv;
66 		}
67 		for (cnt = linecnt; cnt; --cnt)
68 			while ((ch = getchar()) != EOF)
69 				if (putchar(ch) == '\n')
70 					break;
71 	}
72 	/*NOTREACHED*/
73 }
74