C Programming - SPLessons

Command Line Arguments in C

Home > Lesson > Chapter 20
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Command Line Arguments in C

Command Line Arguments in C

shape Description

A useful feature for any program is to accept user input. Suppose user gives a string input, then the getString() prompts the user to give a string while program is running. Sometimes, there may be need to provide the input before the program is actually running. So that, there will be no need to ask the user for additional information while program is running. Providing arguments as the input to the program to perform a specific task from command line during execution is called "Command line arguments". Command line arguments focuses on functioning of program and keep a track of it. If needed, the program can be altered also by using these arguments. For this, two arguments has to be specified in main().They are:
  • There is a possibility to even use the string as the argv elements.
  • arg[0] denotes the path of .exe file. If name is not available, compiler shows the empty string.arg[0] will always be the command and the last element argv[argc] will always be a NULL.
  • argv can also be used as 2D-array and also as null pointer.

shape Syntax

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

shape Example

[c] #include<stdio.h> int main(int argc,char *argv[]) //command line arguments { int i; if (argc==1) { printf("Enter the command line arguments"); return 0; } for(i=0; i<argc; i++) { printf("%s",argv[i]); } return 0; }[/c] Save the above program with some name (like splessons.exe) and run this program. Enter the arguments in the command prompt which are nothing but the command line arguments.

Summary

shape Key Points

  • Command line arguments in C focuses on functioning of program.
  • argc and argv[] are the two command line arguments in main section.