Parsing command-line arguments in C?

后端 未结 12 831
眼角桃花
眼角桃花 2020-11-22 16:23

I\'m trying to write a program that can compare two files line by line, word by word, or character by character in C. It has to be able to read in command line options

12条回答
  •  长情又很酷
    2020-11-22 16:44

    There is a great general-purpose C library libUCW which includes neat command-line option parsing and config file loading.

    The library also comes with good documentation and includes some other useful stuff (fast IO, data structures, allocators, ...) but this can be used separately.

    Example libUCW option parser (from the library docs)

    #include 
    #include 
    
    int english;
    int sugar;
    int verbose;
    char *tea_name;
    
    static struct opt_section options = {
      OPT_ITEMS {
        OPT_HELP("A simple tea boiling console."),
        OPT_HELP("Usage: teapot [options] name-of-the-tea"),
        OPT_HELP(""),
        OPT_HELP("Options:"),
        OPT_HELP_OPTION,
        OPT_BOOL('e', "english-style", english, 0, "\tEnglish style (with milk)"),
        OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "\tAmount of sugar (in teaspoons)"),
        OPT_INC('v', "verbose", verbose, 0, "\tVerbose (the more -v, the more verbose)"),
        OPT_STRING(OPT_POSITIONAL(1), NULL, tea_name, OPT_REQUIRED, ""),
        OPT_END
      }
    };
    
    int main(int argc, char **argv)
    {
      opt_parse(&options, argv+1);
      return 0;
    }
    

提交回复
热议问题