From 9e74b7e754e5f94075e3b41316eb3ec3634a80ee Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 16 Jan 2016 03:10:15 -0700 Subject: [PATCH] proposed cat example implementation --- example/cat/main.zig | 49 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/example/cat/main.zig b/example/cat/main.zig index e1529552d8..44ac1ae084 100644 --- a/example/cat/main.zig +++ b/example/cat/main.zig @@ -1,7 +1,52 @@ export executable "cat"; -pub fn main(argv: [][]u8) i32 => { +import "std.zig"; +pub fn main(args: [][]u8) error => { + const exe = args[0]; + var catted_anything = false; + for (arg in args[1...]) { + if (arg == "-") { + catted_anything = true; + cat_stream(stdin) !! (err) => return err; + } else if (arg[0] == '-') { + return usage(exe); + } else { + var is: InputStream; + is.open(arg, OpenReadOnly) !! (err) => { + stderr.print("Unable to open file: {}", ([]u8])(err)); + return err; + } + defer is.close(); - return 0; + catted_anything = true; + cat_stream(is) !! (err) => return err; + } + } + if (!catted_anything) { + cat_stream(stdin) !! (err) => return err; + } +} + +fn usage(exe: []u8) error => { + stderr.print("Usage: {} [FILE]...\n"); + return error.Invalid; +} + +fn cat_stream(is: InputStream) error => { + var buf: [1024 * 4]u8; + + while (true) { + const bytes_read = is.read(buf); + if (bytes_read < 0) { + stderr.print("Unable to read from stream: {}", ([]u8)(is.err)); + return is.err; + } + + const bytes_written = stdout.write(buf[0...bytes_read]); + if (bytes_written < bytes_read) { + stderr.print("Unable to write to stdout: {}", ([]u8)(stdout.err)); + return stdout.err; + } + } }