liveBook · Manning

Command-line argument

As explained in Systems Programming with Zig

A command line argument is a value supplied to a program when it is invoked from a command-line interface.

A command-line argument is a value supplied when a program is invoked. In a Zig utility, arguments can provide file paths for the program to process. section 3.3.2

Listing 3.7 Cat with arguments and more files
const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const args = try init.minimal.args.toSlice(arena); #1
    const cwd = std.Io.Dir.cwd();

    const stdout_file = std.Io.File.stdout();
    var stdout_buffer: [1024]u8 = undefined;
    var stdout_writer = stdout_file.writer(io, &stdout_buffer);
    const stdout = &stdout_writer.interface;

    for (args[1..]) |filepath| { #2
        const text = try cwd.readFileAlloc(
            filepath,
            io,
            arena,
            .unlimited,
        );
        try stdout.writeAll(text);
    }

    try stdout.flush(); #3
}

This implementation converts the arguments to a slice, skips the executable name, and reads each remaining path. section 3.3.2

Concatenate two files

Run `zig run ./cat_allocating_with_args.zig -- meow.txt woof.txt` to pass two file paths to the utility. section 3.3.2

Build options use command-line flags for a different purpose: they configure values such as reader and writer buffer sizes, which the program can access at compile time. section 3.5.3

How Systems Programming with Zig covers it

How deep it goes
Shows argument acquisition, skipping the executable name, and iterating paths, without demonstrating named-option parsing.
Examples
Demonstrates concatenating meow.txt and woof.txt and configuring reader and writer buffer sizes.
What you can do after
Apply it via Zig's std.process.Init to read file paths and iterate over them in a utility.
How it connects
Connects positional arguments to file I/O and build flags to compile-time configuration.

Also explained in

Compare how 15 books explain command-line argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.