Home » C programming language

C language Command Line Arguments



Sometimes, we need to give input while running the program (command) through the command line, C language has a great feature "Command Line Arguments", and by using this feature we can send our input through the command line to the program.

Let's consider with an example: You have designed a program to count the total number of characters of a text file, and you want to give the file name through the command line while running the program. Like this,

./count Sample1.txt

Here, count is the program name and Sample1.txt is the file name, so here are two command line arguments count and Sample1.txt.

Here is the syntax of main() function with command line arguments

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

Here,

int argc - is the local variable name (you can use any name here), basically argc is the argument count, it will contain the total number of arguments given through the command line (including program name).

char *argv[] - An array of strings, that will contain the strings (character arrays) which is written on the command line.

Consider the following statement

./main Mike 27 "New Delhi" India

Here, total number of arguments will be 5.

Note: if string has space between two words we can put them in double quotes.

Consider the complete program:

#include<stdio.h>

int main(int argc, char* argv[])
{
    int iLoop;
 
    printf("\nTotal number of arguments : %d",argc);
    printf("\nArguments are :\n");
 
    for(iLoop=0;iLoop < argc; iLoop++)
    {
        printf("%s\t",argv[iLoop]);
    }
    
    printf("\n");
    
    return 0;
}

Command Line and Output

./main Mike 27 "New Delhi" India

Total number of arguments : 5 
Arguments are : 
main	Mike	27	New Delhi 	India





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.