Monday 19 June 2023

Command line arguments in C

What are command line arguments?

1.1   why we need command line arguments

The plan or program was performing or executing at command prompt or occasion we are giving the input worth or values as a part of execution. Before starting execution or performance we want to give input values or worth along with the executable filename. For this, the instruct or command line args were using while C executable or performance file name is giving at instruct or command prompt.

command line, arguments in C, declaration of main function
Command line arguments in C Image-1

C provides a fairly or equitably simple mechanism or machine for recover or retrieving command line parameters go into or entered by the user. Command-line disagreement or arguments are given after the name of a program in instructs or command-line operating systems like DOS or Linux, and are move or passed in to the program from the operating system. In fact, main can actually receive or accept two arguments: one argument argc variable or parameter is number of command or instruct line arguments. Second argument argv parameter or variable argument is a full list of all of the instruct or command line arguments.

 

1.2   declaration of main function

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

The digit or integer, argc is the argument count. It is the number of arguments move or passed into the program from the command or instructs line, including the name of the program. *argv[]. The array of nature or character pointers is the listing of all the arguments. You can use each argv component or element just like a string, or use argv as a two size or dimensional array. argv [argc] is a null pointer.

Almost any program or plan that wants its variable or parameters to be set when it is carry out or executed would use this. One common use is to write a task or function that takes the name of a file and outputs the entire text of it onto the screen.

/*Program to Access command line arguments*/

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
printf(“Argc=%d\n”, argc);
for (int i=1; i<argc; i++)
printf(“argv[%d]=%s\n”, I, argv[i]);
return (0);
}
OUTPUT
at command line: ./a.out hello testing one two
argc=5
argv[0]=./prog9
argv[1]=hello
argv[2]=testing
argv[3]=one
argv[4]=two

In this code, the main plan or program accepts two variable or parameters, argv and argc. The argv parameter or variable is an array of pointers to string that carry or contains the parameters entered when the program or plan was call on or invoked at the UNIX command line. The argc digit or integer contains a count of the number of parameters. This certain or particular piece of code types out the command line variable or parameters.


Computer stuff kit tricks of Topics 62.