forked from Heatwave/The-C-Programming-Language-2nd-Edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
37.tail.c
48 lines (36 loc) · 694 Bytes
/
37.tail.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
#include <stdio.h>
#include <string.h>
#define MAXLINES 50000
#define MAXLEN 10000
int mygetline(char *line, int max);
char *alloc(int);
void afree(char*);
main(int argc, char *argv[])
{
int n;
if (argc == 1)
n = 10;
else if (argc == 2 && (*++argv)[0] == '-') {
n = atoi(*argv + 1);
if (n < 1)
n = 10;
} else {
printf("Usage: tail -n\n");
return 1;
}
char line[MAXLEN], *lineptr[MAXLINES];
int len;
char *p;
int lines = 0;
while ((len = mygetline(line, MAXLEN)) > 0) {
p = alloc(len + 1);
strcpy(p, line);
lineptr[lines++] = p;
}
int i = lines - n;
i = (i >= 0) ? i : 0;
while (n-- > 0 && i <= lines) {
printf("%s", lineptr[i++]);
}
return 0;
}