xref: /original-bsd/usr.bin/head/head.c (revision 9d44d164)
1 /*
2  * Copyright (c) 1980, 1987 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1980, 1987 Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)head.c	5.5 (Berkeley) 06/01/90";
16 #endif /* not lint */
17 
18 #include <stdio.h>
19 #include <ctype.h>
20 /*
21  * head - give the first few lines of a stream or of each of a set of files
22  *
23  * Bill Joy UCB August 24, 1977
24  */
25 
26 main(argc, argv)
27 	int	argc;
28 	char	**argv;
29 {
30 	register int	ch, cnt;
31 	int	firsttime, linecnt = 10;
32 
33 	if (argc > 1 && argv[1][0] == '-') {
34 		if (!isdigit(argv[1][1])) {
35 			fprintf(stderr, "head: illegal option -- %c\n", argv[1][1]);
36 			goto usage;
37 		}
38 		if ((linecnt = atoi(argv[1] + 1)) < 0) {
39 usage:			fputs("usage: head [-line_count] [file ...]\n", stderr);
40 			exit(1);
41 		}
42 		--argc; ++argv;
43 	}
44 	/* setlinebuf(stdout); */
45 	for (firsttime = 1, --argc, ++argv;; firsttime = 0) {
46 		if (!*argv) {
47 			if (!firsttime)
48 				exit(0);
49 		}
50 		else {
51 			if (!freopen(*argv, "r", stdin)) {
52 				fprintf(stderr, "head: can't read %s.\n", *argv);
53 				exit(1);
54 			}
55 			if (argc > 1) {
56 				if (!firsttime)
57 					putchar('\n');
58 				printf("==> %s <==\n", *argv);
59 			}
60 			++argv;
61 		}
62 		for (cnt = linecnt; cnt; --cnt)
63 			while ((ch = getchar()) != EOF)
64 				if (putchar(ch) == '\n')
65 					break;
66 	}
67 	/*NOTREACHED*/
68 }
69