Skip to content

Instantly share code, notes, and snippets.

@sleibrock
Last active September 14, 2021 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sleibrock/b1fab9edf40ad7255b21aaa6c1d4c938 to your computer and use it in GitHub Desktop.
Save sleibrock/b1fab9edf40ad7255b21aaa6c1d4c938 to your computer and use it in GitHub Desktop.
GNU Cat but in Zig
//! GNU Cat replacement, but with Zig I guess
/// -- made with love from @sleibrock
///
/// Exists as a proof of concept of general C-like programming using Zig.
/// Compiles to about 62kb compared to GNU/cat's 39kb.
/// @requires "zig-0.8.1"
const std = @import("std");
const io = std.io;
const fs = std.fs;
const os = std.os;
const BufferSize = 1024; // read 1024 bytes at a time
pub fn main() !void {
// set up init vars
const stdout = io.getStdOut().writer();
var buffer_arr: [BufferSize]u8 = undefined;
var arg_index: usize = 1;
while (arg_index < os.argv.len) {
// grab the file name from argv
var fname = os.argv[arg_index];
// create a file lock (is this the best way to do so?)
var file_lock = fs.cwd().openFileZ(fname, .{ .read = true }) catch |err| {
try stdout.print("Error: something bad happened", .{});
return;
};
// defer closing the file to automatically close the file
// at the end of the scope
defer file_lock.close();
// set up reading vars
var index: u64 = 0;
var bytes_read: u64 = 0;
var read_loop = true;
while (read_loop) {
// attempt to read BufferSize bytes with an offset of :index:
bytes_read = file_lock.pread(buffer_arr[0..], index) catch |err| {
try stdout.print("Caught an error reading the file", .{});
return;
};
// output the bytes to stdout
try stdout.print("{s}", .{buffer_arr});
// increment :index: by :bytes_read:
index += bytes_read;
// wipe buffer
buffer_arr = undefined;
// check if continue
if (bytes_read < BufferSize) {
read_loop = false;
}
}
// move the arg counter
arg_index += 1;
}
}
// end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment