Parsing command-line arguments in C?

后端 未结 12 688
眼角桃花
眼角桃花 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:48

    I've found Gengetopt to be quite useful - you specify the options you want with a simple configuration file, and it generates a .c/.h pair that you simply include and link with your application. The generated code makes use of getopt_long, appears to handle most common sorts of command line parameters, and it can save a lot of time.

    A gengetopt input file might look something like this:

    version "0.1"
    package "myApp"
    purpose "Does something useful."
    
    # Options
    option "filename" f "Input filename" string required
    option "verbose" v "Increase program verbosity" flag off
    option "id" i "Data ID" int required
    option "value" r "Data value" multiple(1-) int optional 
    

    Generating the code is easy and spits out cmdline.h and cmdline.c:

    $ gengetopt --input=myApp.cmdline --include-getopt
    

    The generated code is easily integrated:

    #include 
    #include "cmdline.h"
    
    int main(int argc, char ** argv) {
      struct gengetopt_args_info ai;
      if (cmdline_parser(argc, argv, &ai) != 0) {
        exit(1);
      }
      printf("ai.filename_arg: %s\n", ai.filename_arg);
      printf("ai.verbose_flag: %d\n", ai.verbose_flag);
      printf("ai.id_arg: %d\n", ai.id_arg);
      int i;
      for (i = 0; i < ai.value_given; ++i) {
        printf("ai.value_arg[%d]: %d\n", i, ai.value_arg[i]);
      }
    }
    

    If you need to do any extra checking (such as ensuring flags are mutually exclusive), you can do this fairly easily with the data stored in the gengetopt_args_info struct.

提交回复
热议问题