Skip to content

Instantly share code, notes, and snippets.

@yukioc
Created September 20, 2011 08:38
Show Gist options
  • Save yukioc/1228646 to your computer and use it in GitHub Desktop.
Save yukioc/1228646 to your computer and use it in GitHub Desktop.
get command line options
/*
$ gcc arg.c
$ ./a.out -f -s 10 --longflag --longparam=20 aaa
option f
option s with value 10
option longflag
option longparam with value 20
last option aaa
*/
#include <stdio.h>
#include <string.h>
#define ARG_FLAG(s) (strcmp(s,argv[i])==0)
#define ARG_SPARAM(s) ((strcmp(s,argv[i])==0)&&(i+1)<argc&&((r=argv[++i])!=NULL))
#define ARG_LPARAM(s) ((strncmp(s,argv[i],strlen(s))==0)&&((l=strlen(s))<strlen(argv[i]))&&((r=&argv[i][l])!=NULL))
void main(int argc,char*argv[]){
int i;
for (i=1;i<argc;i++){
char*r=NULL;
int l=0;
if (argv[i][0]!='-'){
break;
}else if(ARG_FLAG("--")){
i++;
break;
}else if(ARG_FLAG("-f")){
printf("option f\n");
}else if(ARG_SPARAM("-s")){
printf("option s with value %s\n",r);
}else if(ARG_FLAG("--longflag")){
printf("option longflag\n");
}else if(ARG_LPARAM("--longparam=")){
printf("option longparam with value %s\n",r);
}else{
break;
}
}
if(i<argc){
printf("last option %s\n",argv[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment