1 of 5

Command line arguments

2 of 5

Command line arguments

  • It is possible to pass arguments to main from a command line.
  • For eg, $cp x.c y.c will copy the file x.c into y.c
  • Here, x.c and y.c are command line arguments.
  • These are actually passed to the main function.
  • Actually, in the above example, the main function receives three arguments, viz., “cp”, “x.c” and “y.c”.

2

12/10/2022

3 of 5

Command line arguments

  • int main( int argc, char *argv[ ] );
  • argc contains number of arguments, including the command name itself.
  • So, in $cp x.c y.c

argc will have value equal to 3.

  • So, the value of argc is atleast 1.
  • argv[0] points to “cp”
  • argv[1] points to “x.c”
  • argv[2] points to “y.c”
  • argv[3] is a NULL pointer.

3

12/10/2022

4 of 5

Command line arguments

      • #include<stdio.h>

int main( int argc, char *argv[ ] )

{

int j;

for( j = 1; j < argc; j++)

printf(“%s ”, argv[ j ] );

return 0;

}

      • This is similar to standard echo program.

4

12/10/2022

5 of 5

Copying a file -- example

      • #include<stdio.h>

int main(int argc, char *argv[ ] )

{

FILE *fpr, *fpw; char ch;

fpr = fopen(argv[0], “r”);

fpw = fopen(argv[1], “w”);

if(fpr == NULL || fpw == NULL) {

puts(“error in opening files”);

exit(1);

}

while( (ch = fgetc(fpr)) != EOF)

fputc(ch, fpw);

fclose(fpr); fclose(fpw);

}

5

12/10/2022