C Command Line Arguments

Till now we've been giving inputs through a keyboard. Let's say you want to add up all the numbers in a text a file. Instead of manually typing all the numbers, you can pass the file directly as an argument to your program. C and C++ provides facility to take inputs from the command line. To give inputs from the command line there are two ways:

int main(int argc, char *argv[]) { /* ... */ }
int main(int argc, char **argv) { /* ... */ }

argc(Argument Count) is an integer which stores the number of arguments required including the program name as one of the argument.

argv(Argument Vector) is an array of character pointers pointing to their respective arguments, where argv[0] is the program name and argv[argc] is a NULL pointer.

Let's see an example code which calculates sum of n numbers through command line.

Code

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
    int sum = 0;
    for (int i = 2; i < argc; ++i)
    {
        sum+=atoi(argv[i]);
    }
    printf("%d\n,sum");
}

Terminal

gcc sum.c
./a.out 5 1 2 3 4 5

Output

15

Trending

C Programming

Remember to follow community guidelines and don't go off topic.