In Python, there is an official module called argparse that provides a versatile command-line parser. Things are a little bit different in C, though. The GNU’s getopt() function is used to parse the command-line arguments with limited functionalities. In this post, I will show how to use getopt() to parse command-line arguments in C.
Getopt in an Example
The basic usage of getopt() is as follows:
1
2
#include <unistd.h>
int getopt(int argc, char **argv, char *optstring);
The argc and argv are passed from main() in C. The optstring is a string of characters that specifies the valid options. For example, a string "abc:d:" means that the valid options are -a, -b, -c, and -d. Characters followed by a colon to indicate an option argument is to follow. So in this example, they are -c argument and -d argument. The argument is saved in an external variable optarg as a string.
The getopt() function incrementally parses a command-line argument list argv and returns the next known option character. If there are no more options, -1 is returned. In practice, the getopt() function is used in the following way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int c;
while ((c = getopt(argc, argv, "ab:c")) != -1) {
switch (c) {
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b with value '%s'\n", optarg);
break;
case 'c':
printf("option c\n");
break;
case '?':
printf("unknown option\n");
break;
default:
abort();
}
}
return 0;
}
Limitations
- The
getopt()function does not support long options, only single-character options are supported. - There is no type casting or checking in the arguments, so extra care should be taken to make sure the arguments are correct.
- It cannot generate help messages. You will have to write your own help messages by adding a
-hoption.
Further Reading
Read the getopt(3) manual page using man 3 getopt to learn more about what getopt can do for you. I also found another well-written blog on this topic you may be interested in.
That is all for this post. Hasta Luego.
Comments powered by Disqus.