authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2016-01-16 03:10:15-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2016-01-16 03:10:15-07:00
log9e74b7e754e5f94075e3b41316eb3ec3634a80ee
treeb00e2558151154a64fdc8936f39f9dbb20c8c068
parent5f7685336f2b0bd5e14765d885b0cf87ebe1f578

proposed cat example implementation


1 files changed, 47 insertions(+), 2 deletions(-)

example/cat/main.zig+47-2
......@@ -1,7 +1,52 @@
11export executable "cat";
22
3pub fn main(argv: [][]u8) i32 => {
3import "std.zig";
44
5pub fn main(args: [][]u8) error => {
6 const exe = args[0];
7 var catted_anything = false;
8 for (arg in args[1...]) {
9 if (arg == "-") {
10 catted_anything = true;
11 cat_stream(stdin) !! (err) => return err;
12 } else if (arg[0] == '-') {
13 return usage(exe);
14 } else {
15 var is: InputStream;
16 is.open(arg, OpenReadOnly) !! (err) => {
17 stderr.print("Unable to open file: {}", ([]u8])(err));
18 return err;
19 }
20 defer is.close();
521
6 return 0;
22 catted_anything = true;
23 cat_stream(is) !! (err) => return err;
24 }
25 }
26 if (!catted_anything) {
27 cat_stream(stdin) !! (err) => return err;
28 }
29}
30
31fn usage(exe: []u8) error => {
32 stderr.print("Usage: {} [FILE]...\n");
33 return error.Invalid;
34}
35
36fn cat_stream(is: InputStream) error => {
37 var buf: [1024 * 4]u8;
38
39 while (true) {
40 const bytes_read = is.read(buf);
41 if (bytes_read < 0) {
42 stderr.print("Unable to read from stream: {}", ([]u8)(is.err));
43 return is.err;
44 }
45
46 const bytes_written = stdout.write(buf[0...bytes_read]);
47 if (bytes_written < bytes_read) {
48 stderr.print("Unable to write to stdout: {}", ([]u8)(stdout.err));
49 return stdout.err;
50 }
51 }
752}