Command Line Arguments in C:
What are command line arguments in C?
It is a different method of passing the arguments or values or input to a program by command line. Generally, the command line arguments are used to control our program from outside of the function. As all, you know, the execution of the program starts from the main() function. The command-line arguments are passed to the main() function of the program.
Syntax of Command Line Arguments:
void main(int argc, char *argv[])
{
}
argc: Denotes the number of arguments passed. It returns the count of arguments passed. But the actual count it returns is (count of arguments + 1).
argv: It is a character pointer array, points to the arguments passed. the passed arguments are actually stored in argv.
Note: No need to use scanf() function in this method. The input is directly passed to the pointer array argv[]. We can use any names instead of arc and argv.
Declaration of Command-Line Arguments:
I have passed two arguments 10, 20 as input through the command line.
void sum(int argc, char *argv[])
{
int x=atoi(argv[1]);
int y=atoi(argv[2]);
}
when we passed 10, 20 through the command line, these values are stored as an ASCII value. It is then converted into integer value using atoi() function. These values get stored from index 1. At the index zero, file name will be stored.
Here are some examples using command-line arguments that will help you understand the functioning of these arguments.
Example1: Consider the command-line arguments as 10 and 20.
Program:
Output:
Explanation: In the above example, 10 and 20 are stored in argv[1], argv[2]. In argv[0], file name a(executable file name) is stored. Now, these values are actually stored in ascii values. atoi() function is used to convert ascii value to an inetger. In a similar way to convert into float use atof() function.
Example2: Another example with the input hello world.
Program:
Output:
Explanation: since the input is hello world, the number of arguments is 3. This is because of the file name is also considered as an argument.
In this tutorial, we have discussed how the command line arguments work along with the examples.
prev<---File I/O
No comments:
Post a Comment