Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Created April 9, 2021 09:22
Show Gist options
  • Save matu3ba/e194fffa72dd6a668c91afa1e91ac144 to your computer and use it in GitHub Desktop.
Save matu3ba/e194fffa72dd6a668c91afa1e91ac144 to your computer and use it in GitHub Desktop.
cli_args_handling
const std = @import("std");
const process = std.process;
const mem = std.mem;
const usage: []const u8 =
\\Usage: executable_name [options]
\\
\\ -h Print this help message and exit.
\\ -c <command> Run `sh -c <command>` on startup.
\\
;
//1. iterate arguments: no allocation necessary
pub fn main() anyerror!void {
var it = std.process.args();
// Skip our name
_ = it.nextPosix();
while (it.nextPosix()) |arg| {
if (std.mem.eql(u8, arg, "-h")) {
try std.io.getStdErr().writeAll(usage);
std.os.exit(0);
} else {
try std.io.getStdErr().writeAll(usage);
std.os.exit(1);
}
}
}
//2. save all arguments and free at end of execution
// defer/errdefer: "always run this when exiting scope" or "run this on error when exiting scope"
pub fn main() !void {
var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_instance.deinit(); // this will deinit on error or success
const arena = &arena_instance.allocator;
const args = try process.argsAlloc(arena);
defer process.argsFree(arena, args); // same here
if (args.len <= 1) {
var number_or_error: anyerror!i32 = error.ArgNotFound;
std.log.info("{s}", .{usage});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment