Command Line Arguments in C
The arguments passed from command line are called command line arguments. These arguments are handled by main() function.To support command line argument, you need to change the structure of main() function as given below.
- int main(int argc, char *argv[] )
The argv[] contains the total number of arguments. The first argument is the file name always.
Example
Let's see the example of command line arguments where we are passing one argument with file name.- #include <stdio.h>
- void main(int argc, char *argv[] ) {
- printf("Program name is: %s\n", argv[0]);
- if(argc < 2){
- printf("No argument passed through command line.\n");
- }
- else{
- printf("First argument is: %s\n", argv[1]);
- }
- }
- ./program hello
- program.exe hello
Program name is: program First argument is: hello
- ./program hello c how r u
Program name is: program First argument is: hello
- ./program "hello c how r u"
Program name is: program First argument is: hello c how r u
No comments:
Post a Comment
Please write your view and suggestion....