Linux命令行参数解析——getopt_long

2021-04-18  本文已影响0人  拉普拉斯妖kk
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex); 
/* 程序运行参数结构体 */
struct InputArgs
{
  std::string user_id;
  std::string user_name;
  std::string pwd;

  void printArgs();

  bool checkArgs()
  {
    if (user_id.empty())
    {
      return false;
    }

    if (user_name.empty())
    {
      return false;
    }

    if (pwd.empty())
    {
      return false;
    }

    return true;
  }
};

InputArgs g_input_arg_info;

void InputArgs::printArgs(){
    printf("ARGS:  --= %s\n", userId.c_str());
    printf("        --userName = %s\n", user_name.c_str());
    printf("        --pwd = %s\n", pwd.c_str());
}

/* 参数解析 */
const char* short_options = "i:n:p:";
struct option long_options[] = {
    { "userId", required_argument, NULL, 'i' },
    { "userName", required_argument, NULL, 'n' },
    { "pwd", required_argument, NULL, 'p' },
    { 0, 0, 0, 0 }, 
};

void print_usage(){
    printf("DESCRIPTION\n");
    printf("  --userId, -i\n");
    printf("  --userName, -n\n");
    printf("  --pwd, -p\n");
}

void print_arg(int argc, char *argv[])
{
  for (int i = 0; i < argc; i++)
  {
    printf("%s\n", argv[i]);
  }
}

int parse_arg(int argc, char *argv[])
{
  print_arg(argc, argv);
  int c;
  std::string opt;
  while ((c = getopt_long(argc, argv, short_options, long_options, NULL)) !=
         -1)
  {
    switch (c)
    {
    case 'i':
      opt = optarg;
      g_input_arg_info.user_id = opt;
      break;
    case 'n':
      opt = optarg;
      g_input_arg_info.user_name = opt;
      break;
    case 'p':
      opt = optarg;
      g_input_arg_info.pwd = opt;
      break;
    default:
      return -1;
    }
  }

  if (false == g_input_arg_info.checkArgs())
  {
    return -2;
  }

  return 0;
}

int main(int argc, char *argv[])
{
  if (0 != parse_arg(argc, argv))
  {
    print_usage();
    printf("parse input args failed!\n");
    return 1;
  }

  g_input_arg_info.printArgs();

  // do things here
}
上一篇 下一篇

猜你喜欢

热点阅读