How to access the command line parameters in C
By Flavio Copes
Learn how to access command line parameters in C by using the argc count and argv array in main(int argc, char *argv[]) to read the arguments passed in.
In your C programs, you might have the need to accept parameters from the command line when the command launches.
For simple needs, all you need to do so is change the main() function signature from
int main(void)
to
int main (int argc, char *argv[])
argc is an integer number that contains the number of parameters that were provided in the command line.
argv is an array of strings.
When the program starts, we are provided the arguments in those 2 parameters.
Note that there’s always at least one item in the
argvarray: the name of the program
Let’s take the example of the C compiler we use to run our programs, like this:
gcc hello.c -o hello
If this was our program, we’d have argc being 4 and argv being an array containing
gcchello.c-ohello
Let’s write a program that prints the arguments it receives:
#include <stdio.h>
int main (int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
}
If the name of our program is hello and we run it like this: ./hello, we’d get this as output:
./hello
If we pass some random parameters, like this: ./hello a b c we’d get this output to the terminal:
./hello
a
b
c
Check argc before reading arguments
A common mistake is to read argv[1] assuming the user passed an argument. If they didn’t, you’re reading past the arguments and the behavior is undefined. The program might crash, or worse, appear to work.
Always check argc first:
if (argc < 2) {
printf("Usage: %s <name>\n", argv[0]);
return 1;
}
printf("Hello, %s\n", argv[1]);
Now running ./hello without arguments prints the usage message instead of crashing.
Arguments are always strings
Every item in argv is a string, even when the user types a number. If you run ./hello 42, argv[1] is the string "42", not the number 42.
To use it as a number, convert it with atoi() from stdlib.h:
#include <stdlib.h>
int age = atoi(argv[1]); //42
atoi() returns 0 when the string is not a valid number, so you can’t tell "0" apart from "hello". When that matters, use strtol() instead, which lets you detect the error.
This system works great for simple needs. For more complex needs, like flags with values and optional parameters, there are commonly used packages like getopt.
Want me to talk about your product? You can sponsor this site.