Lesson 54: Command Line Arguments (argc, argv)
C programs often need to accept parameters directly from the user when the program is executed in the terminal. These are known as command line arguments.
The Special main Signature
To access these arguments, main must be declared with two specific parameters:
c int main(int argc, char *argv[]) { // ... code ... }
1. argc (Argument Count)
An integer representing the total number of arguments passed to the program, including the program name itself.
2. argv (Argument Vector)
An array of pointers to character arrays (strings). Each string pointer holds one command line argument.
argv[0]is always the name/path of the executable.argv[1]is the first user-supplied argument.- ... up to
argv[argc - 1].
Example Usage
Assume the program is compiled to app and run as: ./app file.txt 100
c int main(int argc, char *argv[]) { printf("Total arguments: %d\n", argc); // 3
if (argc < 3) {
printf("Usage: %s <filename> <number>\n", argv[0]);
return 1;
}
printf("Argument 1 (Filename): %s\n", argv[1]); // file.txt
printf("Argument 2 (Number as string): %s\n", argv[2]); // 100
// To use argv[2] as an integer, you must convert it:
int num = atoi(argv[2]); // requires <stdlib.h>
printf("Argument 2 (Number as int): %d\n", num);
return 0;
}