Command line arguments are inputs that are passed to a program at the time it is run from the command line. They allow the user to specify certain options or parameters to the program without having to modify the source code or recompile the program.
In C programming language, command line arguments can be accessed within the main() function using the argc and argv parameters. The argc parameter contains the number of command line arguments passed to the program, and the argv parameter is an array of strings containing the actual arguments.
Here is an example of how to access command line arguments in the main() function:
int main(int argc, char *argv[]) {
printf("Number of command line arguments: %dn", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %sn", i, argv[i]);
}
return 0;
}
In this example, the main() function takes two parameters: argc and argv. The printf() function is used to print the number of command line arguments (argc) and the value of each argument (argv[i]) using a for loop.
For example, if this program is run with the command ./program arg1 arg2 arg3, the output would be:
Number of command line arguments: 4
Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
In this example, the argv array contains four elements, with the first element being the name of the program itself (./program) and the remaining elements being the actual command line arguments (arg1, arg2, and arg3).
Command line arguments can be used for a variety of purposes, such as specifying input and output files, setting program options, and providing additional information to the program. They can make programs more flexible and easier to use by allowing users to customize their behavior without having to modify the source code.