Quantcast
Viewing all articles
Browse latest Browse all 2

How to access Linux command line arguments in C code

Have you ever used Linux command line? if yes then you would have definitely come across command line utilities which require arguments. For example basic commands like ‘cat’, ‘rm’ etc require a file name as an argument. Ever wondered how the code is able to access these Linux command line arguments?  In this article, we will understand how the Linux command line arguments are accessed from within the code of an executable in Linux.

Linux command line arguments

The main() function

The main function can be defined in any of the following two valid ways :

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

The second way mentioned above is what is used in case the command line arguments are needed to be accessed in the code.

The ‘argc’ argument holds the number of arguments while the argument ‘argv’ contains the pointer to names of these arguments. Please note that the name of the executable is included as an argument in this list. The first pointer in the array ‘argv’ points to the a string holding the executable name and other arguments are pointed to by the subsequent pointers in the array.

An example

Here is an example code that uses the ‘argc’ and ‘argv’ values to demonstrate how command line arguments can be accessed :

#include<stdio.h>

int main(int argc, char *argv[])
{
    int counter = 0;
    printf("\n The number of command line arguments passed to this executable is [%d]\n",argc);
    printf("\n The arguments are :\n");

    for(;counter

The output of the above code is :

$ ./cmd hi hello 1 2 3 bye

 The number of command line arguments passed to this executable is [7]

 The arguments are :

 [./cmd] 

 [hi] 

 [hello] 

 [1] 

 [2] 

 [3] 

 [bye]

So the output above shows that the code was able to access the command line arguments successfully. Note that the first argument is the name of the binary itself.

The post How to access Linux command line arguments in C code appeared first on MyLinuxBook.


Viewing all articles
Browse latest Browse all 2

Trending Articles