DEV Community

Cover image for You have been zigged (series) : File copy program (From K&R C book)
Black Tornado
Black Tornado

Posted on

You have been zigged (series) : File copy program (From K&R C book)

Lets recreate a C program in zig that will read a byte from stdin and redirects it to stdout. This is a classical Kernighan & Ritchie C program from the book "The C Programming Language". We will also learn about IO redirection.

// io_redir.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;
        };
        try stdout_writer.print("{c}", .{byte});
    }
    try stdout_writer.flush();
}
Enter fullscreen mode Exit fullscreen mode

Lets compile the program using zig build-exe io_redir.zig. This will produce a io_redir.exe in windows which we are going to run in multiple ways. Lets create a text file test.txt in the same folder where io_redir.exe is placed and add some dummy text content in that file.

IO redirection method 1

type test.txt | io_redir.exe
The type command reads all the content of test.txt and writes it out to stdout. The pipe operator takes that and writes it out to stdin of io_redir.exe. io_redir.exe writes it out in stdout.

IO redirection method 2

io_redir.exe < test.txt
The shell directly reads the contents of test.txt and writes it out to stdin of io_redir.exe, which then prints it out.

IO redirection method 3

io_redir.exe < test.txt > out.txt
The shell directly reads the contents of test.txt and writes it out to stdin of io_redir.exe. io_redir.exe writes that content back to its stdout. The shell upon receiving it, writes it to a file with name out.txt.

Thanks for reading. To be continued.

Top comments (0)