Created
April 21, 2018 19:45
-
-
Save dtrugman/7de942c1a0d41dd600863a57bc78bf0c to your computer and use it in GitHub Desktop.
Argument parsing in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
int main(int argc, char ** argv) | |
{ | |
const char * mystr = "default"; | |
int myint = 0; | |
float myfloat = 0.0; | |
bool mybool = false; | |
opterr = 0; | |
int opt; | |
while ((opt = getopt(argc, argv, "bi:f:s:")) != -1) | |
{ | |
switch (opt) | |
{ | |
case 'b': | |
mybool = true; | |
break; | |
case 'i': | |
myint = atof(optarg); | |
break; | |
case 'f': | |
myfloat = atof(optarg); | |
break; | |
case 's': | |
mystr = optarg; | |
break; | |
case '?': | |
printf("unknown option [%c]", optopt); | |
break; | |
} | |
} | |
printf("options:\n" | |
"mystr: [%s]\n" | |
"mybool: [%d]\n" | |
"myint: [%d]\n" | |
"myfloat: [%f]\n", | |
mystr, mybool, myint, myfloat); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment