Update Zig Cat example
* added reading from stdin if no paths are provided * using streams to encapsulate common behaviour in print_from_stream
This commit is contained in:
parent
c36cac1b06
commit
09b4c503b9
@ -1,9 +1,17 @@
|
||||
const std = @import("std");
|
||||
|
||||
pub fn main() !void {
|
||||
if (std.os.argv.len > 1) {
|
||||
handle_file_input();
|
||||
} else {
|
||||
handle_stdin_input();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_file_input() void {
|
||||
for (std.os.argv[1..]) |file_path_sent| {
|
||||
const file_path = std.mem.span(file_path_sent);
|
||||
const file = std.fs.openFileAbsolute(
|
||||
const file = std.fs.cwd().openFile(
|
||||
file_path,
|
||||
.{ .mode = .read_only },
|
||||
) catch |err| {
|
||||
@ -12,17 +20,25 @@ pub fn main() !void {
|
||||
};
|
||||
defer file.close();
|
||||
|
||||
while (true) {
|
||||
var ar = std.ArrayList(u8).init(std.heap.page_allocator);
|
||||
defer ar.deinit();
|
||||
|
||||
file.reader().streamUntilDelimiter(
|
||||
ar.writer(),
|
||||
'\n',
|
||||
null,
|
||||
) catch break;
|
||||
|
||||
std.debug.print("{s}\n", .{ar.items});
|
||||
}
|
||||
print_from_stream(file.reader().any()) catch continue;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_stdin_input() void {
|
||||
print_from_stream(std.io.getStdIn().reader().any()) catch return;
|
||||
}
|
||||
|
||||
pub fn print_from_stream(stream: std.io.AnyReader) !void {
|
||||
while (true) {
|
||||
var line = std.ArrayList(u8).init(std.heap.page_allocator);
|
||||
defer line.deinit();
|
||||
|
||||
try stream.streamUntilDelimiter(
|
||||
line.writer(),
|
||||
'\n',
|
||||
null,
|
||||
);
|
||||
|
||||
std.debug.print("{s}\n", .{line.items});
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user