Command Line Arguments are data passed to a program when it is started from the terminal or command prompt. This allows users to control the program’s behavior or provide file paths without requiring interactive input inside the program.
1. The main() Function Signature
To receive command line arguments, the main() function must be defined with two specific parameters:
int main(int argc, char *argv[]) {
// ...
}
A. argc (Argument Count)
- Type:
int - Purpose: Stores the total number of arguments passed to the program from the command line. This count always includes the program name itself (so
argcis always at least 1).
B. argv (Argument Vector)
- Type:
char *argv[](An array of pointers to characters, or an array of strings). - Purpose: Stores the actual arguments as an array of C strings.
| Index | Content |
argv[0] | The name used to run the program (the executable path). |
argv[1] | The first argument provided by the user. |
argv[2] | The second argument provided by the user, and so on. |
2. Example: Accessing Arguments
Let’s write a program to display all arguments passed to it:
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
printf("Total arguments: %d\n", argc);
printf("--- Arguments List ---\n");
// Loop from index 0 up to (but not including) argc
for (i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Running the Example (Assuming the executable is named app)
Command:
./app my_file.txt -v
Output:
Total arguments: 3
--- Arguments List ---
Argument 0: ./app
Argument 1: my_file.txt
Argument 2: -v
3. Converting String Arguments to Numbers
A crucial point is that all command line arguments are stored as strings (char *). If you need to treat an argument as an integer or a floating-point number, you must explicitly convert it using library functions from <stdlib.h>:
| Function | Purpose |
atoi() | Converts a string to an integer (int). |
atof() | Converts a string to a double (double). |
atol() | Converts a string to a long integer (long). |
Example: Processing a Numerical Argument
#include <stdio.h>
#include <stdlib.h> // For atoi()
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <number>\n", argv[0]);
return 1;
}
// argv[1] contains the argument string (e.g., "123")
int input_num = atoi(argv[1]);
printf("You entered the number: %d\n", input_num);
return 0;
}
