C Command-Line Arguments
Command-line arguments are values given to a program when it starts. In C, they let a program receive filenames, options, numbers, or other text without asking for input later.
To receive command-line arguments, write main with two parameters: argc and argv.
The main Function Parameters
The usual form is:
int main(int argc, char *argv[])
argc is the argument count. It tells you how many strings are in argv. argv is an array of strings. argv[0] is normally the program name, and the values typed after it are stored in argv[1], argv[2], and so on.
| Expression | Meaning |
|---|---|
argc |
The number of command-line strings. |
argv[0] |
The program name or path used to run it. |
argv[1] |
The first argument after the program name. |
argv[argc - 1] |
The last argument. |
Print All Arguments
This program loops through every command-line string and prints its index and value.
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("Argument count: %d\n", argc);
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
If the compiled program is run like this:
./args red blue
Output:
Argument count: 3
argv[0] = ./args
argv[1] = red
argv[2] = blue
The count is 3 because the program name counts as the first string. The two words after it become argv[1] and argv[2].
Check The Number Of Arguments
Always check argc before reading from argv. If your program expects one argument, then argc should be 2: one for the program name and one for the user-provided value.
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: ./showfile filename\n");
return 1;
}
printf("You asked for: %s\n", argv[1]);
return 0;
}
If the compiled program is run like this:
./showfile notes.txt
Output:
You asked for: notes.txt
This program does not open the file yet; it only shows how to receive and validate the filename. If the user forgets the argument, the program prints a short usage message instead of reading argv[1] when it does not exist.
Important Details
argvvalues are strings, even when the user types numbers.- Use functions such as
atoi,strtol, orstrtodwhen you need to convert argument text to numbers. - Arguments with spaces usually need quotes in the shell, such as
./program "hello world". - Do not modify string data from
argvunless you have a specific reason and understand the consequences.
The key idea is that argc tells you how many command-line strings are available, and argv lets you read each one safely by index.
