Home  >  Article  >  Backend Development  >  Example of command line parameters in C language

Example of command line parameters in C language

WBOY
WBOYforward
2023-08-30 15:09:071108browse

Example of command line parameters in C language

When executing C programs, some values ​​can be passed to them from the command line. These values ​​are called Command Line Parameters, and many times they are important to your program, especially when you want to control the program from the outside rather than hardcoding these values ​​within the code.

Command line parameters are processed using main() function parameters, where argc refers to the number of parameters passed, argv[] is an array of pointers to each parameter passed to program. The following is a simple example that checks if there are any arguments provided from the command line and takes appropriate action -

Sample Code

#include <stdio.h>
int main( int argc, char *argv[] ) {
   if( argc == 2 ) {
      printf("The argument supplied is %s</p><p>", argv[1]);
   } else if( argc > 2 ) {
      printf("Too many arguments supplied.</p><p>");
   } else {
      printf("One argument expected.</p><p>");
   }
}

Output

$./a.out testing
The argument supplied is testing

Output

$./a.out testing1 testing2
Too many arguments supplied.

Output

$./a.out
One argument expected

The above is the detailed content of Example of command line parameters in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete