xref: /original-bsd/usr.bin/head/head.c (revision 6f738a42)
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 the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1980, 1987 Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)head.c	5.4 (Berkeley) 06/29/88";
26 #endif /* not lint */
27 
28 #include <stdio.h>
29 #include <ctype.h>
30 /*
31  * head - give the first few lines of a stream or of each of a set of files
32  *
33  * Bill Joy UCB August 24, 1977
34  */
35 
36 main(argc, argv)
37 	int	argc;
38 	char	**argv;
39 {
40 	register int	ch, cnt;
41 	int	firsttime, linecnt = 10;
42 
43 	if (argc > 1 && argv[1][0] == '-') {
44 		if (!isdigit(argv[1][1])) {
45 			fprintf(stderr, "head: illegal option -- %c\n", argv[1][1]);
46 			goto usage;
47 		}
48 		if ((linecnt = atoi(argv[1] + 1)) < 0) {
49 usage:			fputs("usage: head [-line_count] [file ...]\n", stderr);
50 			exit(1);
51 		}
52 		--argc; ++argv;
53 	}
54 	/* setlinebuf(stdout); */
55 	for (firsttime = 1, --argc, ++argv;; firsttime = 0) {
56 		if (!*argv) {
57 			if (!firsttime)
58 				exit(0);
59 		}
60 		else {
61 			if (!freopen(*argv, "r", stdin)) {
62 				fprintf(stderr, "head: can't read %s.\n", *argv);
63 				exit(1);
64 			}
65 			if (argc > 1) {
66 				if (!firsttime)
67 					putchar('\n');
68 				printf("==> %s <==\n", *argv);
69 			}
70 			++argv;
71 		}
72 		for (cnt = linecnt; cnt; --cnt)
73 			while ((ch = getchar()) != EOF)
74 				if (putchar(ch) == '\n')
75 					break;
76 	}
77 	/*NOTREACHED*/
78 }
79