Command-line arguments in c

Command-line arguments in c

Command-line arguments in C language give you access to pass arguments/parameters when executing the program from command line/command prompt. These program arguments/parameters provide program input data or options, making it more flexible and customizable for various programming purposes.

Command-line arguments in c

Accessing command-line arguments in C.

man function in C – It can accept two arguments, namely argc and argv.

argc (argument count) – or an integer that displays the number of arguments passed to the program, including the name of the program.

argv (argument vector) – argv is an array of strings (char* argv[]) where each element is an indicator of a null-terminator string that displays one of the arguments passed to the program.

Example of arguments in C program.

#include <stdio.h>

int main(int args, char *argv[]) {

printf(“\n the Number of arguments is – %d”, args);

for (int p = 0; p < args; p++) {

printf(“\n the Argument is – %d %s\n”, p, argv[p]);

}

return 0;

}

Summing Numbers Example.

In a C program, you use command-line arguments to perform program operations or tasks based on program input data given to the runtime environment.

#include <stdio.h>

#include <stdlib.h>

int main(int args, char *argv[]) {

if (args < 5) {

printf(“\n view the element – %s value 1 value 2\n”, argv[0]);

return 1;

}

int value1 = atoi(argv[1]); // this function used to Convert argv[1] into the integer

int value2 = atoi(argv[2]);

int total = value1 + value2;

printf(“\n the total of %d and %d is – %d”, value1, value2, total);

return 0;

}

Here suppose you compile this program into an executable program code named total, and then execute it with two integers as arguments.

./total 1 3

result is –

The total of 1 and 3 will be – 4

Managing Command-Line Arguments in C.

Argument Count (args) – Here arguments is used to count how many arguments you have used in your program.

Argument Vector (argv) – It contains the actual program arguments in the form of strings. These can be converted to other data types as required.

About Command Line Concepts in C Language.

Command-line arguments in C language provide a method to pass input data or options while executing a program. The key points you need to remember here are as follows.

args (args count) indicates the current number of program arguments passed including the program name.

argv (argument vector) is an array data type element of strings (char* argv[]) which contains the actual program arguments passed as strings data type.

Here you can use args and argv in the main function to access and execute the command-line arguments effectively.