Here we will discuss that there is the technique to pass arguments in the main function at the time of starting a program.
In previous examples, we have observed that the syntax of the main function is either
int main ()
or
int main (void)
In those cases, the main function does not receive any arguments. To receive command-line arguments in the main function, the syntax of the function will be
int main (int argc, char *argv[] )
The first argument of this function is the argument count and the second argument holds the arguments passed in this function. The following program shows how to work with command-line arguments.
Let us try to write a program, where the content of a file will be copied into another file. Here, the source and target file names are provided as command-line arguments.
In previous examples, we have observed that the syntax of the main function is either
int main ()
or
int main (void)
In those cases, the main function does not receive any arguments. To receive command-line arguments in the main function, the syntax of the function will be
int main (int argc, char *argv[] )
The first argument of this function is the argument count and the second argument holds the arguments passed in this function. The following program shows how to work with command-line arguments.
#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.\n");
else
printf("Exactly one argument expected.\n");
return 0;
}
Let us try to write a program, where the content of a file will be copied into another file. Here, the source and target file names are provided as command-line arguments.
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fpsrc, *fptar;
char c;
fpsrc = fopen(argv[1], "r");
fptar = fopen(argv[2], "w");
if(fpsrc == NULL)
{
printf("Unable to open file!");
exit(1);
}
while(1)
{
c = fgetc(fpsrc);
if(c == EOF)
break;
fputc(c, fptar);
}
fclose(fpsrc);
fclose(fptar);
return 0;
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.