DEV Community

Cover image for You have been zigged (series) : Printing command line arguments
Perennial Lorekeeper
Perennial Lorekeeper

Posted on

You have been zigged (series) : Printing command line arguments

Blog no. 02

Introduction

In this program we will accept the command line arguments passed to the program by the user and print them out one by one. In zig, the main function gets instance of a struct std.process.Init. This instance, commonly named init will contain a lot of stuff including the command line arguments. Let's dive into the program.

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

pub fn main(init: std.process.Init) !void {
    const args = try init.minimal.args.toSlice(init.arena.allocator());
    var buffer: [1024]u8 = undefined;
    var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &buffer);
    const stdout_writer = &file_writer.interface;
    try stdout_writer.print("Printing command line arguments...\n\n", .{});
    for (args) |arg| {
        try stdout_writer.print("{s}\n", .{arg});
    }
    try stdout_writer.flush();
}
Enter fullscreen mode Exit fullscreen mode

Let's compile the program.

C:/learn_zig>zig build-exe -O ReleaseSafe argument_printer.zig
Enter fullscreen mode Exit fullscreen mode

Now let's run the program.

C:/learn_zig>argument_printer.exe Osamu Dazai daun ebani
Enter fullscreen mode Exit fullscreen mode

This will print the following content. Note that the first line is the full path of the executable.

Printing command line arguments...

argument_printer.exe
Osamu
Dazai
daun
ebani
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

Top comments (0)