日期:2014-05-16  浏览次数:20779 次

菜鸟求问一个Advanced Linux Programming里的问题
Mark Mitchell,Jeffery Oldham等写的书
里面第二章 Writing Good GNU/Linux Software 的 2.1.3节 Using getopt_long
 
里面程序已经写好,这个程序的意图也知道,已经用gcc编译过了,编译后文件为getopt_long
但是不知道怎么用,怎么测试
网上找半天找不到,我想这么测试来着
./getopt_long -hv 
但是感觉结果乖乖的,不是应该有的
希望高手给知道下,菜鸟求知道啦

代码如下:
C/C++ code

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>

/*The name of this program.*/
const char * program_name;

/*Prints usage information for this program to STREAM(stdout or stderr),
and exit the program with EXIT_CODE.Does not return.*/
void print_usage(FILE * stream, int exit_code){
  fprintf(stream, "Usage: %s options[inputfile ...]\n", program_name);
  fprintf(stream,
      "  -h --help              Display this usage information.\n "
      "  -o --output filename   Write output to file.\n "
      "  -v --verbose           Print verbose messages.\n ");
  exit(exit_code);
}

/*Main program entry point. ARGC contains number of argument list elements;
ARGV is an array of pointers to them.*/
int main(int argc, char * argv[]){

  int next_option;
  /*A string listing valid short options letters.*/
  const char * const short_options = "ho:v";
  /*An array describing valid long options.*/
  const struct option long_options[] = {
    {"help",   0, NULL, 'h'},
    {"output", 1, NULL, 'o'},
    {"verbose",0, NULL, 'v'},
    {NULL,     0, NULL,  0 }   /*required at end of array.*/
  };

  /*the name of the file to receive program output,
  or NULL for standard output.*/
  const char * output_filename = NULL;
  /*whether to display verbose messages.*/
  int verbose = 0;

  /*remember the name of the program,to incorporate in messages.
   The name is stored in argv[0].*/
  program_name = argv[0];

  do{
    next_option = getopt_long(argc, argv, short_options, long_options, NULL);
    switch(next_option){
    case 'h':/*-h or --help*/
      /*User has requested usage information.Print it to standard output,
       and exit with exit code zero(normal termination).*/
      print_usage(stdout, 0);
    case 'o':/*-o or --output*/
      /*This option takes an argument,the name of the output file.*/
      output_filename = optarg;
      break;
    case 'v':/*-v or --verbose*/
      verbose = 1;
      break;
    case '?':/*The user specified an invalid option.*/
      /*Print usage information to standard error,and exit with
             exit code one(abnormal termination).*/
      print_usage(stderr, 1);
    case -1:/*done with options.*/
      break;
    default:/*sth else:unexpected.*/
      abort();
    }
  }
  while(next_option != -1);
  /*Done with options.OPTIND points to first nonoption argument.
   For demonstration purposes,print them if the verbose option was specified.*/
  if(verbose){
    int i;
    for(i = optind; i < argc; ++i)
      printf("Argument: %s\n",argv[i]);
  }
  /*The main program goes here*/

  return 0;
}




------解决方案--------------------
探讨
还是说这个程序只是拿来做说明getopt_long的使用呢?