×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

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.

Command Line Arguments Example

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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.