Everyone start to learn coding by helloworld.c :) Yes, it’s the basic of digital daylife:
Command line
When dealing commandline style coding, every one need to manage the skill of controlling different kind of argument. It is really a dirty job by analyzing
int main(int argc, char *argv[])
But if you are familiar with POSIX style console command, you’ll find it’s argument definitions and help are so elegent and stylish.
Luckily we have a standard GNU C Library function called getopt
In short, we just need to add the include:
#include <getopt.h>
Then start coding with something like:
int c;
opterr = 0;
while ((c = getopt (argc, argv, "abc:")) != -1)
{
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = atoi(optarg);
break;
case '?':
case ':':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n",optopt);
return 1;
default:
abort ();
}
}
The third argument in funtion getopt
defines the commandline option you need; single charactor means it is a switch with no extra argument is needed, on the other hand, if you need extra argument, put a ‘:’ after your option charactor.
Within the switch
statment, you may notice the following case:
argv
that was not included in options
, or a missing option argument, it returns ‘?’ and sets the external variable optopt
to the actual option character.If you carefully read through the document, you will know the library will expose the following global variables:
Sounds like a beautiful story huh? But it do not have a happy ending.
I will discuss the matter and workaround in the next thread: Dealing with args using getopt() [Part.2]