C Programming • C17 baseline, standards-specific features labeled
Command-Line Arguments
Use argc and argv to accept options, validate values, and report usage clearly.
The main function can receive an argument count and an array of strings. argv[0] is conventionally the program name; user-supplied arguments begin at index one. Check argc before reading an argument and parse numeric text with a conversion function rather than assuming it is valid.
Example
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
const char *program = argc > 0 && argv[0] != NULL ? argv[0] : "greet";
fprintf(stderr, "Usage: %s <name>\n", program);
return 2;
}
printf("Hello, %s\n", argv[1]);
return 0;
}
What to expect
Running ./greet Sam prints Hello, Sam. Running it without a name prints a usage hint.
Key idea: Treat every command-line argument as untrusted text and validate it before using it as a number, path, or option.