This repository has been archived by the owner on May 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
more.c
114 lines (98 loc) · 2.39 KB
/
more.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#define MAX(x, y) ((x) > (y) ? (x) : (y))
extern char *optarg;
extern int optind;
int display;
int lines;
int columns;
void more(FILE * fin, char *name)
{
static const char *MORE = "-- MORE --";
static const char *PROMPT = "[Press space to continue, 'q' to quit.]";
assert(256 > columns);
char buf[256];
printf("----------\n");
printf("%s\n", name);
printf("----------\n");
int lineno = 3;
while (fgets(buf, columns, fin)) {
if (lineno++ % lines == 0) {
printf("%s", display ? PROMPT : MORE);
fflush(stdout);
char c;
do {
c = getchar();
if (c == 'q') {
printf("\n");
return ;
}
} while (c != ' ');
printf("\n");
}
printf("%s", buf);
}
}
int main(int argc, char *argv[])
{
const char *PROGNAME = argv[0];
int opt;
while ((opt = getopt(argc, argv, "dn:")) != -1) {
switch (opt) {
case 'd':
display = 1;
break;
case 'n':
lines = MAX(0, atoi(optarg));
break;
default: /* ? */
return -1;
}
}
argc -= optind;
argv += optind;
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) {
perror(PROGNAME);
return -1;
}
if (lines == 0) {
lines = ws.ws_row - 1;
}
columns = ws.ws_col;
struct termios saved_termios, new_termios;
if (tcgetattr(STDIN_FILENO, &saved_termios) == -1) {
perror(PROGNAME);
return -1;
}
new_termios = saved_termios;
new_termios.c_lflag &= ~(ICANON | ECHO);
if (tcsetattr(STDIN_FILENO, TCSANOW, &new_termios) == -1) {
perror(PROGNAME);
return -1;
}
FILE *fin;
while (*argv) {
if ((fin = fopen(*argv, "r")) == NULL) {
perror(PROGNAME);
continue;
}
more(fin, *argv);
if (fclose(fin) == EOF) {
perror(PROGNAME);
}
if (*++argv) {
printf("\n");
}
}
if (tcsetattr(STDIN_FILENO, TCSANOW, &saved_termios) == -1) {
perror(PROGNAME);
return -1;
}
return 0;
}