zig/test/standalone/cat/main.zig

71 lines
1.8 KiB
Zig
Raw Normal View History

2016-04-19 07:42:56 +08:00
const std = @import("std");
const io = std.io;
2019-05-27 11:35:26 +08:00
const process = std.process;
const fs = std.fs;
2017-02-27 03:35:30 +08:00
const mem = std.mem;
const warn = std.debug.warn;
const allocator = std.debug.global_allocator;
2016-01-14 09:15:51 +08:00
2018-02-01 11:48:40 +08:00
pub fn main() !void {
2019-05-27 11:35:26 +08:00
var args_it = process.args();
const exe = try unwrapArg(args_it.next(allocator).?);
2016-01-16 18:10:15 +08:00
var catted_anything = false;
const stdout_file = io.getStdOut();
const cwd = fs.cwd();
while (args_it.next(allocator)) |arg_or_err| {
const arg = try unwrapArg(arg_or_err);
2017-02-27 03:35:30 +08:00
if (mem.eql(u8, arg, "-")) {
2016-01-16 18:10:15 +08:00
catted_anything = true;
try cat_file(stdout_file, io.getStdIn());
2016-01-16 18:10:15 +08:00
} else if (arg[0] == '-') {
return usage(exe);
} else {
const file = cwd.openFile(arg, .{}) catch |err| {
warn("Unable to open file: {}\n", .{@errorName(err)});
2016-01-16 18:10:15 +08:00
return err;
};
defer file.close();
2016-01-14 09:15:51 +08:00
2016-01-16 18:10:15 +08:00
catted_anything = true;
try cat_file(stdout_file, file);
2016-01-16 18:10:15 +08:00
}
}
if (!catted_anything) {
try cat_file(stdout_file, io.getStdIn());
2016-01-16 18:10:15 +08:00
}
}
2018-02-01 11:48:40 +08:00
fn usage(exe: []const u8) !void {
warn("Usage: {} [FILE]...\n", .{exe});
return error.Invalid;
2016-01-16 18:10:15 +08:00
}
fn cat_file(stdout: fs.File, file: fs.File) !void {
var buf: [1024 * 4]u8 = undefined;
2016-01-16 18:10:15 +08:00
while (true) {
const bytes_read = file.read(buf[0..]) catch |err| {
warn("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
}
stdout.write(buf[0..bytes_read]) catch |err| {
warn("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
}
fn unwrapArg(arg: anyerror![]u8) ![]u8 {
return arg catch |err| {
warn("Unable to parse command line: {}\n", .{err});
return err;
};
}