You have been zigged (series) : Accessing environment variables
Blog no. 03 Accessing environment variables Environment variables are key-value pairs given to a process by the operating system right before it starts. They are mainly used to configure the process on runtime. In C/C++, the environment variables are passed to the main function as arguments. In zig, the environment variables are can be accessed from the init object which is passed to the main function as argument. Let's see how that works. Program - Printing all inherited environment variables using zig. To print out all the environment variables, we will utilize the environment variable iterator. // environment_vars1.zig const std = @import ( "std" ); pub fn main ( init : std . process . Init ) ! void { var env_vars_iterator = init . environ_map . iterator (); // setup stdout writer var buffer : [ 1024 ] u8 = undefined ; var file_writer = std . Io . File . Writer . init (. stdout (), init . io , & buffer ); var stdout_writer = & file_writer . interface ; while ( env_vars_iterator . next ()) | env_var | { try stdout_writer . print ( "{s} \n {s} \n\n " , . { env_var . key_ptr .* , env_var . value_ptr .* }); } try stdout_writer . flush (); } You can run the program using zig run environment_vars1.zig . This will print out all the environment variables to console. To build executable zig build-exe -O ReleaseSafe environment_vars1.zig Program - Printing the value of a user selected environment variable using zig. In this program we are going to setup a Reader which can read from stdin . We will first print out the names of all the environment variables using the iterator we used in the above program and then using aforementioned reader instance, we will let the user type in the name of an environment variable. If they entered a existing environment variable name, we will retrieve the value of that environment variable using the get function and print the value of that environment variable. If the user entered a non-existing environment variable name, we will error out u