summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/05.2.c
blob: 592e474ea34266cf7b4f8e4c949ff100d0e91a46 (plain)
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
#include <termio.h>
#include <stdio.h>

main(argc, argv)
int argc;
char **argv;
{
    struct termio tio, tin;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s file [file ...]\n", *argv);
        exit(1);
    }

    /*
     * In real life we'd check the return value of
     * this, since if the input is redirected from a
     * file it will fail.  We are assuming the
     * terminal is always connected to the standard
     * input.
     */
    ioctl(0, TCGETA, &tio);

    tin = tio;
    tin.c_lflag &= ~ECHO;      /* turn off ECHO   */
    tin.c_lflag &= ~ICANON;    /* turn off ICANON */

    /*
     * Emulate CBREAK mode.
     */
    tin.c_cc[VMIN] = 1;
    tin.c_cc[VTIME] = 0;

    /*
     * Set the new modes.  Again we ignore return
     * values.
     */
    ioctl(0, TCSETA, &tin);

    while (--argc)
        more(*++argv);

    /*
     * Reset the old tty modes.
     */
    ioctl(0, TCSETA, &tio);

    exit(0);
}

/*
 * more--display the file.
 */
more(file)
char *file;
{
    FILE *fp;
    int line;
    char linebuf[1024];

    if ((fp = fopen(file, "r")) == NULL) {
        perror(file);
        return;
    }

    /*
     * Print 22 lines at a time.
     */
    for (;;) {
        line = 1;
        while (line < 22) {
            /*
             * If end-of-file, let them hit a key one
             * more time and then go back.
             */
            if (fgets(linebuf, sizeof(linebuf), fp) == NULL) {
                fclose(fp);
                prompt();
                return;
            }

            fwrite(linebuf, 1, strlen(linebuf), stdout);
            line++;
        }

        prompt();
    }
}

/*
 * prompt--prompt for a character.
 */
prompt()
{
    char answer;

    printf("Type any character for next page: ");
    answer = getchar();
    putchar('\n');
}