zig/test/standalone/cat/main.zig

47 lines
1.3 KiB
Zig
Raw Normal View History

2016-04-19 00:42:56 +01:00
const std = @import("std");
const io = std.io;
2019-05-27 04:35:26 +01:00
const process = std.process;
const fs = std.fs;
2017-02-26 19:35:30 +00:00
const mem = std.mem;
const warn = std.log.warn;
2018-02-01 03:48:40 +00:00
pub fn main() !void {
var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_instance.deinit();
const arena = arena_instance.allocator();
const args = try process.argsAlloc(arena);
const exe = args[0];
2016-01-16 10:10:15 +00:00
var catted_anything = false;
const stdout_file = io.getStdOut();
const cwd = fs.cwd();
for (args[1..]) |arg| {
2017-02-26 19:35:30 +00:00
if (mem.eql(u8, arg, "-")) {
2016-01-16 10:10:15 +00:00
catted_anything = true;
try stdout_file.writeFileAll(io.getStdIn(), .{});
} else if (mem.startsWith(u8, arg, "-")) {
2016-01-16 10:10:15 +00:00
return usage(exe);
} else {
const file = cwd.openFile(arg, .{}) catch |err| {
warn("Unable to open file: {s}\n", .{@errorName(err)});
2016-01-16 10:10:15 +00:00
return err;
};
defer file.close();
2016-01-14 01:15:51 +00:00
2016-01-16 10:10:15 +00:00
catted_anything = true;
try stdout_file.writeFileAll(file, .{});
2016-01-16 10:10:15 +00:00
}
}
if (!catted_anything) {
try stdout_file.writeFileAll(io.getStdIn(), .{});
2016-01-16 10:10:15 +00:00
}
}
2018-02-01 03:48:40 +00:00
fn usage(exe: []const u8) !void {
2021-01-03 09:20:37 +00:00
warn("Usage: {s} [FILE]...\n", .{exe});
return error.Invalid;
2016-01-16 10:10:15 +00:00
}