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
Ok let me explain to you why it only compiles using var by a simple example.
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).
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
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.
Sorry to play necromancer on this thread, but this forum post continues to be the first thing that comes up when I search the Web for “zig args”, so I thought it would be nice to have a simple, complete, working example.
No allocations (won’t work on Windows or WASI)
Uses std.os.argv (prepopulated on program startup):
To each their own. Modern Windows (v10, v11) come with Linux VM under the name WSL (Windows Subsystem Linux). Reduces the pressure to support Windows API.
Great point! (And that’s what I’d personally want most of the time, too.) Thanks!
Editing my answer to include that example as well so people have options.