DEV Community

Cover image for You have been zigged (series) : Copying a binary file
Black Tornado
Black Tornado

Posted on

You have been zigged (series) : Copying a binary file

Lets explore how to read contents of a binary file and print it out in stdout. To do this we will use Dir.readFileAlloc() function. Lets first save a demo text file as test.txt in the same folder as where the program lives and have some lorem ipsum in it. (We will be using a text file to test this out, but the API will work for any binary file. Just trust me.)

// filestdio_bin__main.zig
const std = @import("std");

pub fn main(init: std.process.Init) !void {
    var stderr_buffer: [1024]u8 = undefined;
    var stderr_file_writer = std.Io.File.Writer.init(std.Io.File.stderr(), init.io, &stderr_buffer);
    const stderr_writer = &stderr_file_writer.interface;

    const commandline_args = try init.minimal.args.toSlice(init.arena.allocator());
    if (commandline_args.len != 3) { // exe name, input filename and output filename
        try stderr_writer.print("Usage: filestdio_bin__main <input filename> <output filename>\n", .{});
        try stderr_writer.flush();
        return;
    }

    const file_content = try std.Io.Dir.cwd().readFileAlloc(init.io, commandline_args[1], init.gpa, .unlimited);
    defer init.gpa.free(file_content);

    try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = commandline_args[2], .data = file_content });
}

Enter fullscreen mode Exit fullscreen mode

Upon running this program using zig run filestdio_bin__main.zig -- test.txt output.txt we can see the output.txt having the contents of test.txt.

Thanks for reading. To be continued.

Top comments (0)