zig-toybox/src/cat.zig

35 lines
865 B
Zig
Raw Permalink Normal View History

2022-04-23 20:50:55 +02:00
const std = @import("std");
2022-04-25 22:07:04 +02:00
const stdout = std.io.getStdOut().writer();
2022-04-23 20:50:55 +02:00
pub fn main() anyerror!void {
const args = try std.process.argsAlloc(std.heap.page_allocator);
2022-04-23 20:50:55 +02:00
if (args.len <= 1) {
try print_input();
}
2022-04-25 22:07:04 +02:00
for (args[1..]) |f| {
if (std.mem.eql(u8, f, "-")) { try print_input(); }
2022-04-23 20:50:55 +02:00
else { try print_file (f); }
}
}
2022-04-23 20:50:55 +02:00
fn print_input() !void {
2022-04-25 22:07:04 +02:00
try print_all (std.io.getStdIn());
}
2022-04-23 20:50:55 +02:00
fn print_file(dest: []const u8) !void {
var file = try std.fs.cwd().openFile(dest, .{ .mode = .read_only });
defer file.close();
2022-04-25 22:07:04 +02:00
try print_all (file);
}
2022-04-25 22:07:04 +02:00
fn print_all(reader: std.fs.File) !void {
2022-04-23 20:50:55 +02:00
var buffer: [4096]u8 = undefined;
while (true) {
2022-04-25 22:07:04 +02:00
const nbytes = try reader.read(&buffer);
try stdout.print("{s}", .{buffer[0..nbytes]});
2022-04-23 20:50:55 +02:00
if (nbytes == 0) break;
}
}