From 9109646d8fddbc0d53c21254d467013957e5b69c Mon Sep 17 00:00:00 2001 From: Philippe Pittoli Date: Mon, 25 Apr 2022 22:07:04 +0200 Subject: [PATCH] Simpler cat. --- src/cat.zig | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/src/cat.zig b/src/cat.zig index 4c215ca..8ecbd7b 100644 --- a/src/cat.zig +++ b/src/cat.zig @@ -1,5 +1,5 @@ const std = @import("std"); -const lib = @import("./lib.zig"); +const stdout = std.io.getStdOut().writer(); pub fn main() anyerror!void { const args = try std.process.argsAlloc(std.heap.page_allocator); @@ -8,34 +8,27 @@ pub fn main() anyerror!void { try print_input(); } - const files = args[1..]; - for (files) |f| { - if (std.mem.eql(u8, f, "-")) { try print_input(); } + for (args[1..]) |f| { + if (std.mem.eql(u8, f, "-")) { try print_input(); } else { try print_file (f); } } } fn print_input() !void { - const stdin = std.io.getStdIn().reader(); - var buffer: [4096]u8 = undefined; - while (true) { - const nbytes = try stdin.read(&buffer); - lib.print("{s}", .{buffer[0..nbytes]}); - if (nbytes == 0) break; - } + try print_all (std.io.getStdIn()); } fn print_file(dest: []const u8) !void { - // open file and defer closing var file = try std.fs.cwd().openFile(dest, .{ .mode = .read_only }); defer file.close(); + try print_all (file); +} - // read file content and print everything +fn print_all(reader: std.fs.File) !void { var buffer: [4096]u8 = undefined; - var nbytes : u64 = 0; while (true) { - nbytes = try file.read(&buffer); - lib.print("{s}", .{buffer[0..nbytes]}); + const nbytes = try reader.read(&buffer); + try stdout.print("{s}", .{buffer[0..nbytes]}); if (nbytes == 0) break; } }