C Command Line Arguments
We can give values to a program when we start it from the terminal. These are called command line arguments. To receive them, main() takes two parameters.
int main(int argc, char *argv[])
argcis the number of arguments, including the program name.argvis an array of strings.argv[0]is the program name,argv[1]is the first argument, and so on.
Example: add two numbers
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: sum number1 number2\n");
return 1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("Sum = %d\n", a + b);
return 0;
}
Compile it, and then run it with two numbers.
gcc sum.c -o sum
./sum 10 20
Output:
Output of the above program is
Sum = 30
Print all arguments
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Total arguments: %d\n", argc);
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
./show red green blue
Output:
Output of the above program is
Total arguments: 4
Argument 1: red
Argument 2: green
Argument 3: blue
Note:
atoi() returns 0 if the text is not a number, and gives no error. For safe code use strtol(). Arguments with spaces must be written in quotes, like ./show "New Delhi".
You have finished the C tutorial. Now practice with the C exercises, and then try small programs of your own.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |