In previous blog we performed IO redirection and in this one we are going to build on top of it by doing string upper casing the entire stdin content before redirecting it out to stdout. At first glance it sounds like a trivial program not worth paying attention to, but in zig, performing this uppercase operation is different from other languages. As a modern systems programming language, zig aims to be as much as memory safe without forfeiting control over the memory. A core idea of zig is "no hidden memory allocations". Even for std lib functions. If you want to perform an operation, even if that is a standard library function call, you are forced to either create a memory buffer and pass it to that std lib function, or create something called an "memory allocator" and pass it to that std lib function. This forces the developer to always think in terms of allocated memory and hence reduces the chances of memory related issues. Lets use the std.ascii.toUpper() function to uppercase all the content of text.txt before writing to stdout.
// io_redir_uppercase.zig
const std = @import("std");
pub fn main(init: std.process.Init) !void {
// setup stdin reader
var stdin_buffer: [1024]u8 = undefined;
var file_reader = std.Io.File.Reader.init(.stdin(), init.io, &stdin_buffer);
var stdin_reader = &file_reader.interface;
// setup stdin writer
var stdout_buffer: [1024]u8 = undefined;
var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &stdout_buffer);
var stdout_writer = &file_writer.interface;
while (true) {
const byte = stdin_reader.takeByte() catch {
break;
};
const byte_uppercased = std.ascii.toUpper(byte);
try stdout_writer.print("{c}", .{byte_uppercased});
}
try stdout_writer.flush();
}
Instructions to compile and run the program are same as that of previous blog. In the output the contents of test.txt will be uppercased.
Thanks for reading. To be continued.
Top comments (0)