zig/example/cat/main.zig

65 lines
1.7 KiB
Zig
Raw Normal View History

2016-04-19 07:42:56 +08:00
const std = @import("std");
const io = std.io;
const str = std.str;
2016-01-14 09:15:51 +08:00
// TODO var args printing
pub fn main(args: [][]u8) -> %void {
2016-01-16 18:10:15 +08:00
const exe = args[0];
var catted_anything = false;
for (args[1...]) |arg| {
2016-04-19 07:42:56 +08:00
if (str.eql(arg, "-")) {
2016-01-16 18:10:15 +08:00
catted_anything = true;
cat_stream(io.stdin) %% |err| return err;
2016-01-16 18:10:15 +08:00
} else if (arg[0] == '-') {
return usage(exe);
} else {
var is = io.InStream.open(arg) %% |err| {
2016-04-25 02:23:46 +08:00
%%io.stderr.printf("Unable to open file: ");
%%io.stderr.printf(@err_name(err));
%%io.stderr.printf("\n");
2016-01-16 18:10:15 +08:00
return err;
};
defer %%is.close();
2016-01-14 09:15:51 +08:00
2016-01-16 18:10:15 +08:00
catted_anything = true;
cat_stream(is) %% |err| return err;
2016-01-16 18:10:15 +08:00
}
}
if (!catted_anything) {
cat_stream(io.stdin) %% |err| return err;
2016-01-16 18:10:15 +08:00
}
io.stdout.flush() %% |err| return err;
2016-01-16 18:10:15 +08:00
}
fn usage(exe: []u8) -> %void {
2016-04-25 02:23:46 +08:00
%%io.stderr.printf("Usage: ");
%%io.stderr.printf(exe);
%%io.stderr.printf(" [FILE]...\n");
return error.Invalid;
2016-01-16 18:10:15 +08:00
}
fn cat_stream(is: io.InStream) -> %void {
var buf: [1024 * 4]u8 = undefined;
2016-01-16 18:10:15 +08:00
while (true) {
const bytes_read = is.read(buf) %% |err| {
2016-04-25 02:23:46 +08:00
%%io.stderr.printf("Unable to read from stream: ");
%%io.stderr.printf(@err_name(err));
%%io.stderr.printf("\n");
2016-01-23 18:06:29 +08:00
return err;
};
2016-01-23 18:06:29 +08:00
if (bytes_read == 0) {
break;
2016-01-16 18:10:15 +08:00
}
io.stdout.write(buf[0...bytes_read]) %% |err| {
2016-04-25 02:23:46 +08:00
%%io.stderr.printf("Unable to write to stdout: ");
%%io.stderr.printf(@err_name(err));
%%io.stderr.printf("\n");
2016-01-23 18:06:29 +08:00
return err;
};
2016-01-16 18:10:15 +08:00
}
2016-01-14 09:15:51 +08:00
}