zig/example/cat/main.zig

66 lines
1.6 KiB
Zig
Raw Normal View History

2016-01-14 09:15:51 +08:00
export executable "cat";
2016-01-16 18:10:15 +08:00
import "std.zig";
2016-01-14 09:15:51 +08:00
2016-01-19 10:32:27 +08:00
// Things to do to make this work:
// * var args printing
// * %void type
2016-01-19 10:32:27 +08:00
// * defer
// * %return
// * %% operator
// * make main return %void
// * how to reference error values %.Invalid
2016-01-19 10:32:27 +08:00
// * cast err type to string
// * update std API
pub %.Invalid;
2016-01-19 10:32:27 +08:00
pub fn main(args: [][]u8) %void => {
2016-01-16 18:10:15 +08:00
const exe = args[0];
var catted_anything = false;
2016-01-19 10:32:27 +08:00
for (arg, args[1...]) {
2016-01-16 18:10:15 +08:00
if (arg == "-") {
catted_anything = true;
%return cat_stream(stdin);
2016-01-16 18:10:15 +08:00
} else if (arg[0] == '-') {
return usage(exe);
} else {
var is: InputStream;
is.open(arg, OpenReadOnly) %% (err) => {
2016-01-16 18:10:15 +08:00
stderr.print("Unable to open file: {}", ([]u8])(err));
return err;
}
defer is.close();
2016-01-14 09:15:51 +08:00
2016-01-16 18:10:15 +08:00
catted_anything = true;
%return cat_stream(is);
2016-01-16 18:10:15 +08:00
}
}
if (!catted_anything) {
%return cat_stream(stdin)
2016-01-16 18:10:15 +08:00
}
}
fn usage(exe: []u8) %void => {
2016-01-16 18:31:43 +08:00
stderr.print("Usage: {} [FILE]...\n", exe);
return %.Invalid;
2016-01-16 18:10:15 +08:00
}
fn cat_stream(is: InputStream) %void => {
2016-01-16 18:10:15 +08:00
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;
}
}
2016-01-14 09:15:51 +08:00
}