zig/example/cat/main.zig

58 lines
1.5 KiB
Zig
Raw Normal View History

2016-04-19 07:42:56 +08:00
const std = @import("std");
const io = std.io;
2017-02-27 03:35:30 +08:00
const mem = std.mem;
2017-04-04 12:17:24 +08:00
const os = std.os;
2016-01-14 09:15:51 +08:00
2017-04-04 12:17:24 +08:00
pub fn main() -> %void {
const exe = os.args.at(0);
2016-01-16 18:10:15 +08:00
var catted_anything = false;
2017-04-04 12:17:24 +08:00
var arg_i: usize = 1;
while (arg_i < os.args.count()) : (arg_i += 1) {
2017-04-04 12:17:24 +08:00
const arg = os.args.at(arg_i);
2017-02-27 03:35:30 +08:00
if (mem.eql(u8, arg, "-")) {
2016-01-16 18:10:15 +08:00
catted_anything = true;
2017-01-24 15:06:56 +08:00
%return cat_stream(&io.stdin);
2016-01-16 18:10:15 +08:00
} else if (arg[0] == '-') {
return usage(exe);
} else {
2017-04-04 12:17:24 +08:00
var is = io.InStream.open(arg, null) %% |err| {
%%io.stderr.printf("Unable to open file: {}\n", @errorName(err));
2016-01-16 18:10:15 +08:00
return err;
};
2017-04-04 12:17:24 +08:00
defer is.close();
2016-01-14 09:15:51 +08:00
2016-01-16 18:10:15 +08:00
catted_anything = true;
2017-01-24 15:06:56 +08:00
%return cat_stream(&is);
2016-01-16 18:10:15 +08:00
}
}
if (!catted_anything) {
2017-01-24 15:06:56 +08:00
%return cat_stream(&io.stdin);
2016-01-16 18:10:15 +08:00
}
2017-01-24 15:06:56 +08:00
%return io.stdout.flush();
2016-01-16 18:10:15 +08:00
}
2017-04-04 12:17:24 +08:00
fn usage(exe: []const u8) -> %void {
%%io.stderr.printf("Usage: {} [FILE]...\n", exe);
return error.Invalid;
2016-01-16 18:10:15 +08:00
}
2017-01-06 07:50:36 +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[0..]) %% |err| {
%%io.stderr.printf("Unable to read from stream: {}\n", @errorName(err));
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| {
%%io.stderr.printf("Unable to write to stdout: {}\n", @errorName(err));
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
}