命令行参数的分析

出处: 作者: 日期:2007年11月26日 15时19分

/* 这个实例是从 GNU Libc 手册上看到的 */

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

int main (int argc, char **argv)
{
int c;

while (1)
{
struct option long_options[] =
{
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
/* 返回字符c,等同于 -c 选项 */
{"create", 0, 0, 'c'},
{"file", 1, 0, 0},
/* 数组结束 */
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;

c = getopt_long (argc, argv, "abc:d:",
long_options, &option_index);

/* Detect the end of the options. */
if (c == -1)
break;

switch (c)
{
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s\n", optarg);
break;

case 'a':
puts ("option -a\n");
break;

case 'b':
puts ("option -b\n");
break;

/* 可能是-c --creat参数指出来的 */
case 'c':
printf ("option -c with value `%s'\n", optarg);
break;

case 'd':
printf ("option -d with value `%s'\n", optarg);
break;
}
}

exit (0);
}

当我们输入了错误的选项后,系统会给出错误的提示,如果我们想屏蔽这个信息,我们可以设置opterr为0,对于错误的选项,函数分析时候返回一个'?'字符.我们可以自己对这个字符进行处理.

最后更新时间:2008-03-28 14:00:39
共2页: 上一页 [1] 2 下一页
文章评论
共有 0 位网友发表了评论
用户名: 新注册) 密码: 匿名评论 [查看所有评论]

评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
您可以用以下几种方式找到此文章

考试全流程