Last active
April 11, 2023 21:23
-
-
Save hibiii/9b525a45369f2428742de9addbf39832 to your computer and use it in GitHub Desktop.
Example cat program in Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cat example in zig - by hibi | |
const std = @import("std"); | |
// good practices | |
const logger = std.log.scoped(.cat); | |
pub fn main() !void { | |
const stdout = std.io.getStdOut(); | |
var args = std.process.args(); | |
defer args.deinit(); | |
// Skip the executable name | |
_ = args.skip(); | |
while (args.next()) |arg| { | |
var file = std.fs.cwd().openFile(arg, .{ .mode = .read_only }) catch |err| { | |
logger.err("unable to open file \"{s}\": {}", .{ arg, err }); | |
continue; | |
}; | |
defer file.close(); | |
// x86 page | |
const BUF_SIZE = 4096; | |
var buf: [BUF_SIZE]u8 = undefined; | |
in_file: while (true) { | |
const bytes_read = file.read(&buf) catch |err| { | |
logger.err("unable to read file \"{s}\": {}", .{ arg, err }); | |
break :in_file; | |
}; | |
if (bytes_read <= 0) break :in_file; | |
// Instead of using C-brained null terminator, we make a slice out | |
// of the buffer. Also, easier to read. | |
const slice = buf[0..bytes_read]; | |
_ = try stdout.write(slice); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment