Command line arguments

A description of how to receive command line arguments in C. Command line arguments can be taken as arguments to the main function.

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

}

The first argument is the number of command line arguments. It is an int type.

The second argument is the array type of "char *". Command line arguments are passed as an array of strings.

Note that in C, the name of the executed program is also included as part of the command line arguments.

for example

./test apple orange banana

When executed with, argv becomes as follows.

"./test", "apple", "orange", "banana"

The names argc and argv can be anything, but I will introduce them with the names described in the C language specification.

Sample command line arguments

It receives command line arguments and outputs the contents as they are.

// test.c
#include <stdio.h>
#include <stdint.h>

int main (int argc, char * argv []) {
  for (int32_t i = 0; i <argc; i ++) {
    printf("%s\n", argv [i]);
  }
}

Let's compile and run it like this:

gcc -o test test.c && ./test apple orange banana

The output result is as follows.

./test
apple
orange
banana

Associated Information