.
[coreutils.git] / src / head.c
bloba0415801e6a11239bfa5b301e21b27261127a985
1 /* head -- output first part of file(s)
2 Copyright (C) 1989, 1990, 1991, 1995 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Options: (see usage)
19 Reads from standard input if no files are given or when a filename of
20 ``-'' is encountered.
21 By default, filename headers are printed only if more than one file
22 is given.
23 By default, prints the first 10 lines (head -n 10).
25 David MacKenzie <djm@gnu.ai.mit.edu> */
27 #include <config.h>
29 #include <stdio.h>
30 #include <getopt.h>
31 #include <sys/types.h>
32 #include "system.h"
33 #include "version.h"
34 #include "error.h"
36 /* Number of lines/chars/blocks to head. */
37 #define DEFAULT_NUMBER 10
39 /* Size of atomic reads. */
40 #define BUFSIZE (512 * 8)
42 /* Number of bytes per item we are printing.
43 If 0, head in lines. */
44 static int unit_size;
46 /* If nonzero, print filename headers. */
47 static int print_headers;
49 /* When to print the filename banners. */
50 enum header_mode
52 multiple_files, always, never
55 int safe_read ();
57 /* The name this program was run with. */
58 char *program_name;
60 /* Have we ever read standard input? */
61 static int have_read_stdin;
63 /* If nonzero, display usage information and exit. */
64 static int show_help;
66 /* If nonzero, print the version on standard output then exit. */
67 static int show_version;
69 static struct option const long_options[] =
71 {"bytes", required_argument, NULL, 'c'},
72 {"lines", required_argument, NULL, 'n'},
73 {"quiet", no_argument, NULL, 'q'},
74 {"silent", no_argument, NULL, 'q'},
75 {"verbose", no_argument, NULL, 'v'},
76 {"help", no_argument, &show_help, 1},
77 {"version", no_argument, &show_version, 1},
78 {NULL, 0, NULL, 0}
81 static void
82 usage (int status)
84 if (status != 0)
85 fprintf (stderr, _("Try `%s --help' for more information.\n"),
86 program_name);
87 else
89 printf (_("\
90 Usage: %s [OPTION]... [FILE]...\n\
91 "),
92 program_name);
93 printf (_("\
94 Print first 10 lines of each FILE to standard output.\n\
95 With more than one FILE, precede each with a header giving the file name.\n\
96 With no FILE, or when FILE is -, read standard input.\n\
97 \n\
98 -c, --bytes=SIZE print first SIZE bytes\n\
99 -n, --lines=NUMBER print first NUMBER lines instead of first 10\n\
100 -q, --quiet, --silent never print headers giving file names\n\
101 -v, --verbose always print headers giving file names\n\
102 --help display this help and exit\n\
103 --version output version information and exit\n\
105 SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
106 If -VALUE is used as first OPTION, read -c VALUE when one of\n\
107 multipliers bkm follows concatenated, else read -n VALUE.\n\
108 "));
110 exit (status);
113 /* Convert STR, a string of ASCII digits, into an unsigned integer.
114 Return -1 if STR does not represent a valid unsigned integer. */
116 static long
117 atou (const char *str)
119 int value;
121 for (value = 0; ISDIGIT (*str); ++str)
122 value = value * 10 + *str - '0';
123 return *str ? -1 : value;
126 static void
127 parse_unit (char *str)
129 int arglen = strlen (str);
131 if (arglen == 0)
132 return;
134 switch (str[arglen - 1])
136 case 'b':
137 unit_size = 512;
138 str[arglen - 1] = '\0';
139 break;
140 case 'k':
141 unit_size = 1024;
142 str[arglen - 1] = '\0';
143 break;
144 case 'm':
145 unit_size = 1048576;
146 str[arglen - 1] = '\0';
147 break;
151 static void
152 write_header (const char *filename)
154 static int first_file = 1;
156 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), filename);
157 first_file = 0;
160 static int
161 head_bytes (const char *filename, int fd, long int bytes_to_write)
163 char buffer[BUFSIZE];
164 int bytes_read;
166 while (bytes_to_write)
168 bytes_read = safe_read (fd, buffer, BUFSIZE);
169 if (bytes_read < 0)
171 error (0, errno, "%s", filename);
172 return 1;
174 if (bytes_read == 0)
175 break;
176 if (bytes_read > bytes_to_write)
177 bytes_read = bytes_to_write;
178 if (fwrite (buffer, 1, bytes_read, stdout) == 0)
179 error (1, errno, _("write error"));
180 bytes_to_write -= bytes_read;
182 return 0;
185 static int
186 head_lines (const char *filename, int fd, long int lines_to_write)
188 char buffer[BUFSIZE];
189 int bytes_read;
190 int bytes_to_write;
192 while (lines_to_write)
194 bytes_read = safe_read (fd, buffer, BUFSIZE);
195 if (bytes_read < 0)
197 error (0, errno, "%s", filename);
198 return 1;
200 if (bytes_read == 0)
201 break;
202 bytes_to_write = 0;
203 while (bytes_to_write < bytes_read)
204 if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0)
205 break;
206 if (fwrite (buffer, 1, bytes_to_write, stdout) == 0)
207 error (1, errno, _("write error"));
209 return 0;
212 static int
213 head (const char *filename, int fd, long int number)
215 if (unit_size)
216 return head_bytes (filename, fd, number);
217 else
218 return head_lines (filename, fd, number);
221 static int
222 head_file (const char *filename, long int number)
224 int fd;
226 if (!strcmp (filename, "-"))
228 have_read_stdin = 1;
229 filename = _("standard input");
230 if (print_headers)
231 write_header (filename);
232 return head (filename, 0, number);
234 else
236 fd = open (filename, O_RDONLY);
237 if (fd >= 0)
239 int errors;
241 if (print_headers)
242 write_header (filename);
243 errors = head (filename, fd, number);
244 if (close (fd) == 0)
245 return errors;
247 error (0, errno, "%s", filename);
248 return 1;
252 void
253 main (int argc, char **argv)
255 enum header_mode header_mode = multiple_files;
256 int exit_status = 0;
257 long number = -1; /* Number of items to print (-1 if undef.). */
258 int c; /* Option character. */
260 program_name = argv[0];
261 setlocale (LC_ALL, "");
262 bindtextdomain (PACKAGE, LOCALEDIR);
263 textdomain (PACKAGE);
265 have_read_stdin = 0;
266 unit_size = 0;
267 print_headers = 0;
269 if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
271 /* Old option syntax; a dash, one or more digits, and one or
272 more option letters. Move past the number. */
273 for (number = 0, ++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
274 number = number * 10 + *argv[1] - '0';
275 /* Parse any appended option letters. */
276 while (*argv[1])
278 switch (*argv[1])
280 case 'b':
281 unit_size = 512;
282 break;
284 case 'c':
285 unit_size = 1;
286 break;
288 case 'k':
289 unit_size = 1024;
290 break;
292 case 'l':
293 unit_size = 0;
294 break;
296 case 'm':
297 unit_size = 1048576;
298 break;
300 case 'q':
301 header_mode = never;
302 break;
304 case 'v':
305 header_mode = always;
306 break;
308 default:
309 error (0, 0, _("unrecognized option `-%c'"), *argv[1]);
310 usage (1);
312 ++argv[1];
314 /* Make the options we just parsed invisible to getopt. */
315 argv[1] = argv[0];
316 argv++;
317 argc--;
320 while ((c = getopt_long (argc, argv, "c:n:qv", long_options, (int *) 0))
321 != EOF)
323 switch (c)
325 case 0:
326 break;
328 case 'c':
329 unit_size = 1;
330 parse_unit (optarg);
331 goto getnum;
332 case 'n':
333 unit_size = 0;
334 getnum:
335 /* FIXME: use xstrtoul instead. */
336 number = atou (optarg);
337 if (number == -1)
338 error (1, 0, _("invalid number `%s'"), optarg);
339 break;
341 case 'q':
342 header_mode = never;
343 break;
345 case 'v':
346 header_mode = always;
347 break;
349 default:
350 usage (1);
354 if (show_version)
356 printf ("head - %s\n", version_string);
357 exit (0);
360 if (show_help)
361 usage (0);
363 if (number == -1)
364 number = DEFAULT_NUMBER;
366 if (unit_size > 1)
367 number *= unit_size;
369 if (header_mode == always
370 || (header_mode == multiple_files && optind < argc - 1))
371 print_headers = 1;
373 if (optind == argc)
374 exit_status |= head_file ("-", number);
376 for (; optind < argc; ++optind)
377 exit_status |= head_file (argv[optind], number);
379 if (have_read_stdin && close (0) < 0)
380 error (1, errno, "-");
381 if (fclose (stdout) == EOF)
382 error (1, errno, _("write error"));
384 exit (exit_status);