2016-01-14 01:15:51 +00:00
|
|
|
export executable "cat";
|
|
|
|
|
2016-01-16 10:10:15 +00:00
|
|
|
import "std.zig";
|
2016-01-14 01:15:51 +00:00
|
|
|
|
2016-01-19 02:32:27 +00:00
|
|
|
// Things to do to make this work:
|
|
|
|
// * var args printing
|
|
|
|
// * defer
|
|
|
|
// * cast err type to string
|
2016-01-24 08:34:48 +00:00
|
|
|
// * string equality
|
2016-01-21 01:18:50 +00:00
|
|
|
|
2016-01-26 03:27:57 +00:00
|
|
|
pub fn main(args: [][]u8) -> %void {
|
2016-01-16 10:10:15 +00:00
|
|
|
const exe = args[0];
|
|
|
|
var catted_anything = false;
|
2016-01-19 02:32:27 +00:00
|
|
|
for (arg, args[1...]) {
|
2016-01-16 10:10:15 +00:00
|
|
|
if (arg == "-") {
|
|
|
|
catted_anything = true;
|
2016-01-21 01:18:50 +00:00
|
|
|
%return cat_stream(stdin);
|
2016-01-16 10:10:15 +00:00
|
|
|
} else if (arg[0] == '-') {
|
|
|
|
return usage(exe);
|
|
|
|
} else {
|
2016-01-26 06:56:46 +00:00
|
|
|
var is = input_stream_open(arg, OpenReadOnly) %% |err| {
|
2016-01-26 03:27:57 +00:00
|
|
|
%%stderr.print("Unable to open file: {}", ([]u8)(err));
|
2016-01-16 10:10:15 +00:00
|
|
|
return err;
|
2016-01-26 06:56:46 +00:00
|
|
|
};
|
2016-01-16 10:10:15 +00:00
|
|
|
defer is.close();
|
2016-01-14 01:15:51 +00:00
|
|
|
|
2016-01-16 10:10:15 +00:00
|
|
|
catted_anything = true;
|
2016-01-21 01:18:50 +00:00
|
|
|
%return cat_stream(is);
|
2016-01-16 10:10:15 +00:00
|
|
|
}
|
|
|
|
}
|
2016-01-21 01:18:50 +00:00
|
|
|
if (!catted_anything) {
|
|
|
|
%return cat_stream(stdin)
|
2016-01-16 10:10:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-26 03:27:57 +00:00
|
|
|
fn usage(exe: []u8) -> %void {
|
2016-01-23 10:06:29 +00:00
|
|
|
%%stderr.print("Usage: {} [FILE]...\n", exe);
|
2016-01-24 08:34:48 +00:00
|
|
|
return error.Invalid;
|
2016-01-16 10:10:15 +00:00
|
|
|
}
|
|
|
|
|
2016-01-26 03:27:57 +00:00
|
|
|
fn cat_stream(is: InputStream) -> %void {
|
2016-01-26 06:56:46 +00:00
|
|
|
var buf: [1024 * 4]u8 = undefined;
|
2016-01-16 10:10:15 +00:00
|
|
|
|
|
|
|
while (true) {
|
2016-01-25 22:45:05 +00:00
|
|
|
const bytes_read = is.read(buf) %% |err| {
|
2016-01-23 10:06:29 +00:00
|
|
|
%%stderr.print("Unable to read from stream: {}", ([]u8)(err));
|
|
|
|
return err;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (bytes_read == 0) {
|
|
|
|
break;
|
2016-01-16 10:10:15 +00:00
|
|
|
}
|
|
|
|
|
2016-01-25 22:45:05 +00:00
|
|
|
stdout.write(buf[0...bytes_read]) %% |err| {
|
2016-01-23 10:06:29 +00:00
|
|
|
%%stderr.print("Unable to write to stdout: {}", ([]u8)(err));
|
|
|
|
return err;
|
2016-01-16 10:10:15 +00:00
|
|
|
}
|
|
|
|
}
|
2016-01-14 01:15:51 +00:00
|
|
|
}
|