C in 100 Seconds: Command Line Arguments
Video: C in 100 Seconds: Command Line Arguments — argc and argv | Episode 38 by Taught by Celeste AI - AI Coding Coach
Watch full page →Command Line Arguments
Every C program can accept input from the command line through two parameters in main: argc (argument count) and argv (argument values).
argc and argv
int main(int argc, char *argv[]) {
printf("argc: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
argc is always at least 1 because argv[0] is the program name itself. Every argument after that is a string in the argv array.
Parsing Flags
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-v") == 0) {
verbose = 1;
} else if (strcmp(argv[i], "-n") == 0 && i + 1 < argc) {
count = atoi(argv[++i]);
} else {
name = argv[i];
}
}
Loop from index 1 to skip the program name. Use strcmp to match flags and atoi to convert string arguments to integers.
Two Runs
With no arguments: argc is 1, defaults apply. With ./args Alice -n 3 -v: argc is 5, the name is Alice, count is 3, and verbose is on.
Student Code
Try it yourself: episode38/args.c