Configuration
Getopt long
In HTTPd, you will have to parse the arguments that are given to your program.
We encourage you to use the getopt_long function. In this section, we will
focus on how it works and on how you will be able to use it.
For the sake of the example, here is the command line that we want to parse:
42sh$ ./bin --httpd "I love" --acus "ARE THE BEST"
Here is how we can parse it using getopt_long:
#include <getopt.h>
#include <stddef.h>
#include <stdio.h>
int main(int argc, char **argv)
{
struct option options[] = { { "httpd", required_argument, NULL, 'h' },
{ "acus", required_argument, NULL, 'a' },
{ NULL, 0, NULL, 0 } };
char ch;
while ((ch = getopt_long(argc, argv, "ha", options, NULL)) != -1)
{
switch (ch)
{
case 'h':
printf("httpd option: %s\n", optarg);
break;
case 'a':
printf("acus option: %s\n", optarg);
break;
}
}
return 1;
}
The struct option is used to tell how the option should be formatted. In our
case, httpd is the option, required_argument means that the httpd option
requires a value ("I love" in the example), NULL means that we do not need
flags and h is the character that will be returned by getopt_long if it
finds the option httpd.
The variable optarg is a global variable that you can use. It will contain the
value of the option.
The result of the command will be:
42sh$ ./bin --httpd "I love" --acus "ARE THE BEST"
httpd option: I love
acus option: ARE THE BEST