xref: /freebsd/usr.bin/head/head.c (revision cdd6ea94b0a4ec29cfaf5243fd52fd032da92bf6)
1 /*
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1987, 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1980, 1987, 1992, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)head.c	8.2 (Berkeley) 5/4/95";
41 #endif
42 #endif /* not lint */
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/types.h>
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <getopt.h>
51 #include <inttypes.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 /*
58  * head - give the first few lines of a stream or of each of a set of files
59  *
60  * Bill Joy UCB August 24, 1977
61  */
62 
63 static void head(FILE *, int);
64 static void head_bytes(FILE *, off_t);
65 static void obsolete(char *[]);
66 static void usage(void);
67 
68 static const struct option long_opts[] =
69 {
70 	{"bytes",	required_argument,	NULL, 'c'},
71 	{"lines",	required_argument,	NULL, 'n'},
72 	{NULL,		no_argument,		NULL, 0}
73 };
74 
75 int
76 main(int argc, char *argv[])
77 {
78 	FILE *fp;
79 	char *ep;
80 	off_t bytecnt;
81 	int ch, first, linecnt, eval;
82 
83 	linecnt = -1;
84 	eval = 0;
85 	bytecnt = -1;
86 
87 	obsolete(argv);
88 	while ((ch = getopt_long(argc, argv, "+n:c:", long_opts, NULL)) != -1) {
89 		switch(ch) {
90 		case 'c':
91 			bytecnt = strtoimax(optarg, &ep, 10);
92 			if (*ep || bytecnt <= 0)
93 				errx(1, "illegal byte count -- %s", optarg);
94 			break;
95 		case 'n':
96 			linecnt = strtol(optarg, &ep, 10);
97 			if (*ep || linecnt <= 0)
98 				errx(1, "illegal line count -- %s", optarg);
99 			break;
100 		case '?':
101 		default:
102 			usage();
103 			/* NOTREACHED */
104 		}
105 	}
106 	argc -= optind;
107 	argv += optind;
108 
109 	if (linecnt != -1 && bytecnt != -1)
110 		errx(1, "can't combine line and byte counts");
111 	if (linecnt == -1)
112 		linecnt = 10;
113 	if (*argv != NULL) {
114 		for (first = 1; *argv != NULL; ++argv) {
115 			if ((fp = fopen(*argv, "r")) == NULL) {
116 				warn("%s", *argv);
117 				eval = 1;
118 				continue;
119 			}
120 			if (argc > 1) {
121 				(void)printf("%s==> %s <==\n",
122 				    first ? "" : "\n", *argv);
123 				first = 0;
124 			}
125 			if (bytecnt == -1)
126 				head(fp, linecnt);
127 			else
128 				head_bytes(fp, bytecnt);
129 			(void)fclose(fp);
130 		}
131 	} else if (bytecnt == -1)
132 		head(stdin, linecnt);
133 	else
134 		head_bytes(stdin, bytecnt);
135 
136 	exit(eval);
137 }
138 
139 static void
140 head(FILE *fp, int cnt)
141 {
142 	char *cp;
143 	size_t error, readlen;
144 
145 	while (cnt != 0 && (cp = fgetln(fp, &readlen)) != NULL) {
146 		error = fwrite(cp, sizeof(char), readlen, stdout);
147 		if (error != readlen)
148 			err(1, "stdout");
149 		cnt--;
150 	}
151 }
152 
153 static void
154 head_bytes(FILE *fp, off_t cnt)
155 {
156 	char buf[4096];
157 	size_t readlen;
158 
159 	while (cnt) {
160 		if ((uintmax_t)cnt < sizeof(buf))
161 			readlen = cnt;
162 		else
163 			readlen = sizeof(buf);
164 		readlen = fread(buf, sizeof(char), readlen, fp);
165 		if (readlen == 0)
166 			break;
167 		if (fwrite(buf, sizeof(char), readlen, stdout) != readlen)
168 			err(1, "stdout");
169 		cnt -= readlen;
170 	}
171 }
172 
173 static void
174 obsolete(char *argv[])
175 {
176 	char *ap;
177 
178 	while ((ap = *++argv)) {
179 		/* Return if "--" or not "-[0-9]*". */
180 		if (ap[0] != '-' || ap[1] == '-' || !isdigit(ap[1]))
181 			return;
182 		if ((ap = malloc(strlen(*argv) + 2)) == NULL)
183 			err(1, NULL);
184 		ap[0] = '-';
185 		ap[1] = 'n';
186 		(void)strcpy(ap + 2, *argv + 1);
187 		*argv = ap;
188 	}
189 }
190 
191 static void
192 usage(void)
193 {
194 
195 	(void)fprintf(stderr, "usage: head [-n lines | -c bytes] [file ...]\n");
196 	exit(1);
197 }
198