Waypoint Waypoint - 2 months ago 17
C Question

C - reading command line parameters

I have made little program for computing PI as an Integral. Now I am facing question how to extend it to compute integral, which will be given as an extra parameter when starting and app. Does anyone knows how to deal with such a parameter in a program? Thanks


When you write your main function, you typically seen one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

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

I'm using GCC 4.5 to compile this, it's a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral

A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
    if (argc < 2) // no arguments were passed
        // do something

    if (strcmp("integral", argv[1]) == 0)
        runIntegral(...); //or something
        // do something else.

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.