source: trunk/minix/commands/simple/head.c@ 15

Last change on this file since 15 was 9, checked in by Mattia Monga, 14 years ago

Minix 3.1.2a

File size: 1.3 KB
Line 
1/* head - print the first few lines of a file Author: Andy Tanenbaum */
2
3#include <errno.h>
4#include <stdlib.h>
5#include <stdio.h>
6#include <string.h>
7
8#define DEFAULT 10
9
10_PROTOTYPE(int main, (int argc, char **argv));
11_PROTOTYPE(void do_file, (int n, FILE *f));
12_PROTOTYPE(void usage, (void));
13
14int main(argc, argv)
15int argc;
16char *argv[];
17{
18 FILE *f;
19 int n, k, nfiles;
20 char *ptr;
21
22 /* Check for flag. Only flag is -n, to say how many lines to print. */
23 k = 1;
24 ptr = argv[1];
25 n = DEFAULT;
26 if (argc > 1 && *ptr++ == '-') {
27 k++;
28 n = atoi(ptr);
29 if (n <= 0) usage();
30 }
31 nfiles = argc - k;
32
33 if (nfiles == 0) {
34 /* Print standard input only. */
35 do_file(n, stdin);
36 exit(0);
37 }
38
39 /* One or more files have been listed explicitly. */
40 while (k < argc) {
41 if (nfiles > 1) printf("==> %s <==\n", argv[k]);
42 if ((f = fopen(argv[k], "r")) == NULL)
43 fprintf(stderr, "%s: cannot open %s: %s\n",
44 argv[0], argv[k], strerror(errno));
45 else {
46 do_file(n, f);
47 fclose(f);
48 }
49 k++;
50 if (k < argc) printf("\n");
51 }
52 return(0);
53}
54
55
56
57void do_file(n, f)
58int n;
59FILE *f;
60{
61 int c;
62
63 /* Print the first 'n' lines of a file. */
64 while (n) switch (c = getc(f)) {
65 case EOF:
66 return;
67 case '\n':
68 --n;
69 default: putc((char) c, stdout);
70 }
71}
72
73
74void usage()
75{
76 fprintf(stderr, "Usage: head [-n] [file ...]\n");
77 exit(1);
78}
Note: See TracBrowser for help on using the repository browser.