Argument-parsing helpers for C/Unix

前端 未结 7 2121
清酒与你
清酒与你 2020-11-28 04:53

I know of the following:

  • The venerable getopt(3)
  • The extended getopt_long
  • glibc\'s argp parser for Unix-style argum
相关标签:
7条回答
  • 2020-11-28 05:39

    I'm not too fond of getopt either (although it's pretty standard). One solution I've made is the function argopt(). It's C compatible, can be used to test whether flags are set as well as reading options with values. It only supports short options (e.g. -h) although writing a similar function for long options (e.g. --help) shouldn't be too difficult. See example:

    int main(int argc, char **argv){
    
        if(argopt(argc, argv, 'p')) printf("-p is set\n");
        if(argopt(argc, argv, 'q')) printf("-q is set\n");
    
        const char *f = argopt(argc, argv, 'f');
        if(f) printf("-f is %s\n",f);
    
        return 0;
    }
    

    Example from command line:

    $./main -f input.txt -rq
    -q is set
    -f is input.txt
    

    Disclaimer: I made this function for fun, intending for it to be short, C-compatible, easy to use, and have no dependencies. Here it is:

    const char* argopt(int argc, const char *const *argv, char key){
    
        for(int i=1; i<argc; i++){
            const char *c = argv[i];
            if(*c!='-') continue;
            while(*++c) if(*c==key) return argv[(i+1)%argc];
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题