Read command line arguments

Hi,

I’m looking for a simple way to read the command line arguments, passed to my program. I don’t want to use a full fledged command line parser, since this program is for personal use only and I hope to learn zig a little more with this approach.

Is there a zig equivalent to argc and *argv[] like in C?

Take a look at std.process.args() and related. The source files for zig’s standard library are very easy to follow. Mine are located at homebrew/Cellar/zig/0.9.1/lib/zig/std.

thank you for your reply.
I struggle to do it right. To be honest, I’m a little bit frustrated, I’m sure this is an easy task, but the lack of documentation makes this really hard.

var args = std.process.args(); //why does this only compile with "var"??
_ = args.skip(); //to skip the zig call

const allocator = std.heap.page_allocator;
const file_path = try args.next(allocator); 
...

but the compiler want’s me to remove the try before args.next(allocator), but why?

Note: English is not my native language therefore i always struggled to write English but i tried my best to explain you if you get confused let me know :slight_smile:

Ok let me explain to you why it only compiles using var by a simple example.

const Student = struct {
    name: []const u8,

    pub fn init() Student {
        return Student{.name = undefined};
    }

    pub fn setName(self: *Student, name: []const u8) void {
        self.name = name;
};

pub fn main() !void {
    var student1 = Student.init();
    student1.setName("foo");
}

In the above example method setName sets the member name therefore inorder to change the member of itself it needs to take a mutable pointer to itself. But if you decalre a student1 with const it will be become immutable so when you call student1.setName it will be passed as *const Student (immutable) where setName expects *Student (mutable).

In this case std.process.args() returns a ArgIterator here is the actual code of it

For second problem: Why compiler wants you to remove try keyword?

try keyword is used when a function returns either an error or a value. Which means when you use const val = try someFun() it basically means “if someFunc() returns an error catch it and return it to the caller otherwise store the actual value to val”

In your case next() returns an optional value.
So to unwrap the actual value you can do const file_path = args.next().?; Notice .? at the end which basically means if next() returns a value give me that value otherwise panic with the message attempt to use null value

I hope i explain to you properly.

Doc Links:
try keyword
Optionals

2 Likes

An alternative is to use std.process.argsAlloc() so that you can allocate a copy of the argv as an array of strings, which might be easier to iterate over.

I wrote a library for argument parsing: https://github.com/sam701/zig-cli The design is inspired by the urfave/cli golang library.