cat.zig: simplification.
This commit is contained in:
parent
444078fcc6
commit
7204ade9e3
51
cat/cat.zig
51
cat/cat.zig
@ -1,57 +1,34 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const stdout = std.io.getStdOut().writer();
|
||||||
fn print(comptime format: []const u8, args: anytype) void {
|
|
||||||
const stdout = std.io.getStdOut().writer();
|
|
||||||
nosuspend stdout.print(format, args) catch return;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn print_input() !void {
|
|
||||||
const stdin = std.io.getStdIn().reader();
|
|
||||||
var buffer: [4096]u8 = undefined;
|
|
||||||
while (true) {
|
|
||||||
const nbytes = try stdin.read(&buffer);
|
|
||||||
print("{s}", .{buffer[0..nbytes]});
|
|
||||||
if (nbytes == 0) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fatal(comptime format: []const u8, args: anytype) noreturn {
|
|
||||||
std.log.err(format, args);
|
|
||||||
std.process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const usage = "usage: cat [files]";
|
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
if (args.len <= 1) {
|
if (args.len <= 1) {
|
||||||
std.log.info("{s}", .{usage});
|
|
||||||
fatal("expected command argument", .{});
|
|
||||||
}
|
|
||||||
|
|
||||||
const files = args[1..];
|
|
||||||
for (files) |f| {
|
|
||||||
if (std.mem.eql(u8, f, "-")) {
|
|
||||||
try print_input();
|
try print_input();
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
try print_file (f);
|
for (args[1..]) |f| {
|
||||||
}
|
if (std.mem.eql(u8, f, "-")) { try print_input(); }
|
||||||
|
else { try print_file (f); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn print_input() !void {
|
||||||
|
try print_all (std.io.getStdIn());
|
||||||
|
}
|
||||||
|
|
||||||
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);
|
||||||
print("{s}", .{buffer[0..nbytes]});
|
try stdout.print("{s}", .{buffer[0..nbytes]});
|
||||||
if (nbytes == 0) break;
|
if (nbytes == 0) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user