Created
January 14, 2024 14:25
-
-
Save haseeb-heaven/88b705b84fd0d19575278acfb00c7f68 to your computer and use it in GitHub Desktop.
This is small method library to parse all arguments from command line in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> // Include header for standard input/output functions | |
#include <assert.h> // Include header for the assert function | |
#define NOB_ASSERT assert // Define NOB_ASSERT as an alias for assert | |
// Function to shift the first argument from argv and update argc | |
char *nob_shift_args(int *argc, char ***argv) { | |
NOB_ASSERT(*argc > 0); // Assert that there's at least one argument | |
char *result = **argv; // Store the first argument in result | |
(*argv) += 1; // Increment argv to point to the next argument | |
(*argc) -= 1; // Decrement argc to reflect the removed argument | |
return result; // Return the shifted argument | |
} | |
int main(int argc, char *argv[]) { | |
if (argc < 2) { // Check if there are sufficient arguments | |
printf("Usage: %s <argument1> <argument2> ...\n", argv[0]); // Print usage message if not | |
return 1; // Exit with an error code | |
} | |
printf("All arguments:\n"); // Print a heading for the argument list | |
int arg_index = 1; // Initialize a counter for argument numbers (starting from 1, as 0 is the program name) | |
while (argc > 0) { // Continue as long as there are arguments remaining | |
char *arg = nob_shift_args(&argc, &argv); // Shift and retrieve the next argument using nob_shift_args | |
printf("Argument %d: %s\n", arg_index, arg); // Print the argument number and value | |
arg_index++; // Increment the argument counter | |
} | |
return 0; // Exit with a success code | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment