summaryrefslogtreecommitdiff
path: root/appl/cmd/cat.b
blob: 24d62372b7755c828be3aecb1393a3f786cf9e15 (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
implement Cat;

include "sys.m";
include "draw.m";

Cat: module
{
	init:	fn(ctxt: ref Draw->Context, argv: list of string);
};

sys: Sys;
stdout: ref Sys->FD;

init(nil: ref Draw->Context, argl: list of string)
{
	sys = load Sys Sys->PATH;

	stdout = sys->fildes(1);

	argl = tl argl;
	if(argl == nil)
		argl = "-" :: nil;
	while(argl != nil) {
		cat(hd argl);
		argl = tl argl;
	}
}

cat(file: string)
{
	n: int;
	fd: ref Sys->FD;
	buf := array[8192] of byte;

	if(file == "-")
		fd = sys->fildes(0);
	else {
		fd = sys->open(file, sys->OREAD);
		if(fd == nil) {
			sys->fprint(sys->fildes(2), "cat: cannot open %s: %r\n", file);
			raise "fail:bad open";
		}
	}
	for(;;) {
		n = sys->read(fd, buf, len buf);
		if(n <= 0)
			break;
		if(sys->write(stdout, buf, n) < n) {
			sys->fprint(sys->fildes(2), "cat: write error: %r\n");
			raise "fail:write error";
		}
	}
	if(n < 0) {
		sys->fprint(sys->fildes(2), "cat: read error: %r\n");
		raise "fail:read error";
	}
}