forked from aamine/stdlinux2-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhead3.c
58 lines (50 loc) · 1.09 KB
/
head3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void do_head(FILE *f, long nlines);
#define DEFAULT_N_LINES 10
int
main(int argc, char *argv[])
{
int opt;
long nlines = DEFAULT_N_LINES;
while ((opt = getopt(argc, argv, "n:")) != -1) {
switch (opt) {
case 'n':
nlines = atol(optarg);
break;
case '?':
fprintf(stderr, "Usage: %s [-n LINES] [file...]\n", argv[0]);
exit(1);
}
}
if (optind == argc) {
do_head(stdin, nlines);
} else {
int i;
for (i = optind; i < argc; i++) {
FILE *f;
f = fopen(argv[i], "r");
if (!f) {
perror(argv[i]);
exit(1);
}
do_head(f, nlines);
fclose(f);
}
}
exit(0);
}
static void
do_head(FILE *f, long nlines)
{
int c;
if (nlines <= 0) return;
while ((c = getc(f)) != EOF) {
if (putchar(c) < 0) exit(1);
if (c == '\n') {
nlines--;
if (nlines == 0) return;
}
}
}