C Command Line Arguments
Syntax
int main(int argc, char *argv[])
Example
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments passed: %d\n", argc);
printf("Arguments passed: ");
for(int i = 0; i < argc; i++) {
printf("%s ", argv[i]);
}
return 0;
}
Output
$./example arg1 arg2 arg3 arg4
Number of arguments passed: 5
Arguments passed: ./example arg1 arg2 arg3 arg4
Explanation
Command-line arguments are used to pass information to a program when it is executed. In C, the main()
function accepts two parameters: argc
(argument count) and argv
(argument vector).
The argc
parameter specifies the number of command-line arguments passed to the program, while argv
is a pointer to an array of strings that contain the arguments themselves.
Use
Command-line arguments can be used to provide input to a command-line utility or program, or to modify its behavior. They can also be used to specify file names, directories, or other settings.
Important Points
- Command-line arguments are passed to
main()
by the operating system. - The
argv
parameter is an array of strings. - The first element of
argv
is always the name of the program. - The
argc
parameter specifies the number of elements inargv
. - Command-line arguments can be used to configure and customize program behavior.
Summary
C command-line arguments provide a way to pass information to a program when it is executed. The main()
function accepts two parameters: argc
(argument count) and argv
(argument vector). argc
specifies the number of command-line arguments passed to the program, while argv
is an array of strings that contain the arguments themselves. Command-line arguments can be used to configure and customize program behavior, and are a useful way to provide input to command-line utilities and programs.