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