summaryrefslogtreecommitdiff
path: root/more.c
blob: 9e1512775f66894a511e2c9a900e8d3d18bf7402 (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
/* See LICENSE file for copyright and license details. */
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>

#include "util.h"

#define COLUMNS 80
#define ROWS 25
#define BUFSIZE 10

static void
usage(void)
{
	eprintf("usage: %s [file ...]\n", argv0);
}

int
main(int argc, char *argv[])
{
	int fd;
	char c;
	int col;
	int row;
	int buf[BUFSIZE];

	ARGBEGIN {
	default:
		usage();
	} ARGEND

	if (argc < 1 && isatty(STDIN_FILENO)) {
		usage();
	}
	
	if (isatty(STDIN_FILENO)) {
		if ((fd = open(*argv, O_RDONLY)) < 0) {
			weprintf("open %s:", *argv);
			return 0;
			
		}
	} else {
		fd = STDIN_FILENO;
	}
	
	col = 0;
	row = 0;
	while (read(fd, &c, 1) != 0) {
		switch (c) {
			case '\r':
				col = 0;
				break;
			
			case '\n':
				col = 0;
				row++;
				break;
			
			case '\t':
				col = ((col+1) | 0x07)+1;
				break;
			
			case '\b':
				if (col>0) {
					col--;
				}
				break;
				
			default:
				col++;
				break;
		}
		putchar(c);
		
		if (row<ROWS) {
			continue;
		}
		
		puts("--more--");
		
		if (read(STDIN_FILENO, &buf, BUFSIZE) < 0) {
			goto END;
		}
		
		col = 0;
		row = 0;		
	}
	
END:
	if (fd > STDERR_FILENO) {
		close(fd);
	}
	
	return 0;
}