Simpler cat.

master
Philippe Pittoli 2022-04-25 22:07:04 +02:00
parent 16d6067f21
commit 9109646d8f
1 changed files with 9 additions and 16 deletions

View File

@ -1,5 +1,5 @@
const std = @import("std"); const std = @import("std");
const lib = @import("./lib.zig"); const stdout = std.io.getStdOut().writer();
pub fn main() anyerror!void { pub fn main() anyerror!void {
const args = try std.process.argsAlloc(std.heap.page_allocator); const args = try std.process.argsAlloc(std.heap.page_allocator);
@ -8,34 +8,27 @@ pub fn main() anyerror!void {
try print_input(); try print_input();
} }
const files = args[1..]; for (args[1..]) |f| {
for (files) |f| { if (std.mem.eql(u8, f, "-")) { try print_input(); }
if (std.mem.eql(u8, f, "-")) { try print_input(); }
else { try print_file (f); } else { try print_file (f); }
} }
} }
fn print_input() !void { fn print_input() !void {
const stdin = std.io.getStdIn().reader(); try print_all (std.io.getStdIn());
var buffer: [4096]u8 = undefined;
while (true) {
const nbytes = try stdin.read(&buffer);
lib.print("{s}", .{buffer[0..nbytes]});
if (nbytes == 0) break;
}
} }
fn print_file(dest: []const u8) !void { fn print_file(dest: []const u8) !void {
// open file and defer closing
var file = try std.fs.cwd().openFile(dest, .{ .mode = .read_only }); var file = try std.fs.cwd().openFile(dest, .{ .mode = .read_only });
defer file.close(); 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 buffer: [4096]u8 = undefined;
var nbytes : u64 = 0;
while (true) { while (true) {
nbytes = try file.read(&buffer); const nbytes = try reader.read(&buffer);
lib.print("{s}", .{buffer[0..nbytes]}); try stdout.print("{s}", .{buffer[0..nbytes]});
if (nbytes == 0) break; if (nbytes == 0) break;
} }
} }