Wednesday, 23 August 2017

Command Line Argument

C language is known as a language of building block of function. It means all the things achieved by the language using function.

A function is a set of some valid statements of language. Which achieved some specific task? You need to know some information about function before using it.
  • Function name
  • Return type
  • Arguments its take


So as we seen what are the attributes of function. We also know that function may or may not takes argument and main is also a function.

Main is an entry point of c language program program execution and it can take argument in some case. When main function takes argument it’s known as command line argument. You can provide argument value while running program on DOS command window with your program name.

main(int argc, char *argv[])

argc is number of argument given at command line.
argv  is character array which stores arguments

Following program will demonstrate display a file content using command line argument.

#include<stdio.h>
void main()
{
     char ch;
     FILE *pt;
     pt=fopen("Test.txt","r");
     if(pt==NULL)
          puts("\nUnable to open file");
     else
     {
          while(1)
          {
              ch=getc(pt);
              if(ch==EOF)
                   break;
              printf("%c",ch);
          }
     }

}