用C写命令行程序,最常碰到cmd option解析,libopt提供了lib来帮助我们简化了这个事情。下面是个GNU风格的命令帮助:
 
linux-2ssv:/share/cj_prog_practise/cprogram/opt_parse # ./popt -?
Usage: popt [OPTIONS]* <port>
  -b, –bps=BPS     signaling rate in bits-per-second
  -c, –crnl        expand cr characters to cr/lf sequences
  -h, –hwflow      use hardware (RTS/CTS) flow control
  -n, –noflow      use no flow control
  -r, –raw         don’t perform any character conversions
  -s, –swflow      use software (XON/XOF) flow control
Help options:
  -?, –help        Show this help message
  –usage           Display brief usage message
 
让我们来看看使用libopt的常用手法:
1。定义popOption数组
   struct poptOption optionsTable[] = {
            { "bps", ‘b’, POPT_ARG_INT, &speed, 0,
                "signaling rate in bits-per-second", "BPS" },
            { "crnl", ‘c’, 0, 0, ‘c’,
                "expand cr characters to cr/lf sequences" },
            { "hwflow", ‘h’, 0, 0, ‘h’,
                "use hardware (RTS/CTS) flow control" },
            { "noflow", ‘n’, 0, 0, ‘n’,
                "use no flow control" },
            { "raw", ‘r’, 0, &raw, 0,
                "don’t perform any character conversions" },
            { "swflow", ‘s’, 0, 0, ‘s’,
                "use software (XON/XOF) flow control" } ,
            POPT_AUTOHELP
            { NULL, 0, 0, NULL, 0 }
2. 获得popContext
 optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0);
 
3. poptGetNextOpt用来解析每个option
   while ((c = poptGetNextOpt(optCon)) >= 0) {
      switch (c) {
         case ‘c’:
            buf[i++] = ‘c’;
            break;
         。。。
      }
   }
 
4. 最后用poptGetArg读取每个参数
   portname = poptGetArg(optCon);
 
 
Advertisements