C command line parameters
When executing a program, you can pass values from the command line to the C program. These values are called command line parameters, and they are important to the program, especially if you want to control the program from the outside rather than hardcoding these values within the code.
Command line parameters are processed using main() function parameters, where argc refers to the number of parameters passed in, and argv[] is a pointer Array pointing to each argument passed to the program. The following is a simple example that checks whether parameters are provided on the command line and performs corresponding actions based on the parameters:
#include <stdio.h>int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); }}
Using a parameter, compile and execute the above code, it will produce the following results:
$./a.out testingThe argument supplied is testing
Use two parameters, compile and execute the above code, it will produce the following results:
$./a.out testing1 testing2Too many arguments supplied.
Without passing any parameters, compile and execute the above code, it will produce the following results:
$./a.outOne argument expected
It should be noted that argv[0] stores the name of the program, argv[1] is a pointer to the first command line argument, *argv[n ] is the last parameter. If no arguments are supplied, argc will be 1, otherwise if one argument is passed, argc will be set to 2.
Multiple command line parameters are separated by spaces, but if the parameters themselves contain spaces, the parameters should be placed inside double quotes "" or single quotes '' when passing the parameters. Let's rewrite the above example to have a space, then you can pass the views like this and put them in double quotes or single quotes """". Let's rewrite the above example to pass a command line argument to the program placed inside double quotes:
#include <stdio.h>int main( int argc, char *argv[] ) { printf("Program name %s\n", argv[0]); if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); }}
Using a simple argument separated by spaces and enclosed in double quotes, compile and execute the above code, which produces the following results:
$./a.out "testing1 testing2"Progranm name ./a.outThe argument supplied is testing1 testing2