| ... | @@ -1,7 +1,52 @@ | ... | @@ -1,7 +1,52 @@ |
| 1 | export executable "cat"; | 1 | export executable "cat"; |
| 2 | | 2 | |
| 3 | pub fn main(argv: [][]u8) i32 => { | 3 | import "std.zig"; |
| 4 | | 4 | |
| | 5 | pub 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(); |
| 5 | | 21 | |
| 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 | |
| | 31 | fn usage(exe: []u8) error => { |
| | 32 | stderr.print("Usage: {} [FILE]...\n"); |
| | 33 | return error.Invalid; |
| | 34 | } |
| | 35 | |
| | 36 | fn 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 | } |
| 7 | } | 52 | } |