Command Line Arguments in C Programming Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Command Line Arguments in C Programming Language

Share This
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.

#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; if(argc != 2) { printf("Number of arguments must be two."); exit(1); } 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; }

To create an executable/binary file by name mycp, you may compile the code using following syntax.
$gcc test.c -o mycp
To run the program, you may use the following command on your terminal.
$./mycp sourcefile.ext destfile.ext

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.