In C programming often a situation may come where we want to pass the information into a program during the execution of the program. These values are called Command Line Arguments(CLA).
The “main()” function handles the command line argument.
Syntax:
int main( int argc, char *argv[] )
{
}
Here, argc refers to the number of arguments passed and argv[] is a pointer array that points to each argument.
Note:
argc
– argument count in command line argv[0]
– holds the name of the program
argv[1]
– holds the first command line argument,
argv[2]
– holds the second command line argument and and so on.
If no argument is supplied, argc will be 1
Program1: Write a program to take one value from user during execution as a Command Line Argument in C Language
1 2 3 4 5 6 7 8 | #include <stdio.h> int main(int argc, char *argv[] ) { printf("\nNo of command line arguments are %d",argc); printf("\nProgram name is: %s ", argv[0]); printf("\nCommand line argument is: %s", argv[1]); return 0; } |
Note: Suppose the above program name is “CLA”.
Run this program as follows in Linux:
./CLA hello
Here hello is a command line argument.
Run this program as follows in Windows from the command line:
program.exe hello
Here hello is a command line argument.
Program name is: CLA
Command line argument is: hello
Program 2: Write A Program to Add two numbers using Command Line Argument in C Programming
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> #include <stdlib.h> int main(int argc, char * argv[]) { int sum; if (argc != 3) { printf("Please enter two integer numbers to add"); exit(1); } sum = atoi(argv[1]) + atoi(argv[2]); printf("Sum is %d", sum); return 0; } |
to convert string to integer atoi()
method is used. Similar to convert string to float atof()
is used
gcc add.c
./a.out 5 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) // command line arguments { if(argc!=5) { printf("Pass four arguments from command line"); exit(1); } printf("\n Program name : %s \n", argv[0]); printf("\n 1st arg : %s ", argv[1]); printf("\n 2nd arg : %s ", argv[2]); printf("\n 3rd arg : %s ", argv[3]); printf("\n 4th arg : %s ", argv[4]); return 0; } |
gcc names.c ./names RAM MOHAN SOHAN RAMESH
1st arg : RAM
2nd arg : MOHAN
3rd arg : SOHAN
4th arg : RAMESH
Program4: Find the radius of the circle and take the area input from the command line argument
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h> #include<stdlib.h> int main(int argc, char * argv[]) { float area, radius; if (argc != 2) { printf("Please enter circle radius"); exit(1); } radius = atof(argv[1]); area = 3.14 * radius * radius; printf("Area of circle = %0.2f\n", area); return 0; } |
gcc circle.c ./circle 5