Command line Arguments In C

Command line Arguments In C

Alright, guys let’s talk about command line arguments, command line arguments are a way we allow the user to provide data to our program at runtime instead of while the program is running.

Example

./4-add_practice 1 10 100

The bash program name is the first arg followed by the 1, 10 and 100, so we basically have 4 command line args for the above program

Declaring main for command line arg program

we can’t use `int main(void){}` if we want to collect more data from the user at the command line, instead, we declare main as follows

`int main (int argc, char *argv[]){}`, these two special args enable us to know what data is provided at the command line and how much data they provided.

Understanding the arguments

\>- `argc` also known as argument count: is the count of arguments provided in the commandline starting from the name of the program, count starts from 1; data type integer

\>- `argv[]` also known as argument vector: is the list or array of arguments or strings provided in the command line, the data type is string or array of chars. Since argv is an array the first argument will be at index 0.

#include <stdio.h>

typedef char *string;

int main(int argc, string argv[])
{

    if (argc == 2)

    {

        printf("hello, %s count is : %d\n", argv[1], argc);

    }

    else

    {

        printf("hello, world\n");

    }

}

The program prints hello, and the second argument is provided in the command line if the argument is equal to 2, else just print hello, the world if the is less than two or greater than two.

Output

(base) ayo@hp-HP-Pavilion-g6-Notebook-PC:~/Desktop/Study/Practice$ ./argv Ayo

hello, Ayo arg count is: 2
(base) ayo@hp-HP-Pavilion-g6-Notebook-PC:~/Desktop/Study/Practice$ ./argv

hello, world