荔园在线
荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀
[回到开始]
[上一篇][下一篇]
发信人: FreeBSD (FreeBSD), 信区: Linux
标 题: 容易忽视的函数和调用(四)-- getopt(zz)
发信站: BBS 荔园晨风站 (Sat Jan 8 17:52:28 2000), 站内信件
【 以下文字转载自 FreeBSD 的信箱 】
【 原文由 liugang.bbs@melon.gznet.edu.cn 所发表 】
发信人: cpu (奔腾的心), 信区: Solaris
标 题: 容易忽视的函数和调用(四)-- getopt(zz)
发信站: 华南网木棉站 (Thu Oct 8 16:38:13 1998), 转信
NAME
getopt - get option letter from argument vector
SYNOPSIS
#include <stdlib.h>
int getopt(int argc, char * const *argv,
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
这是个什么函数呢?如果泥想把命令行的输入选项做得比较unix,
象tar -xvf ...的风格,就用这个函数来parse命令行参数吧。大
概解释一下这个函数,最好自己看man。
argc是要分析的选项串指针数组argv的长度;argv[]是要分析的选
项串序列;optstring是选项字母集合,比如tar命令里的xvf三个字
母全都是,那么optstring至少是"xvf",如果某个选项字母后面跟
有冒号,那么表明这个选项字母后应该跟有一个参数。比如命令
command -a -b paramb -cde
那么b选项后面的paramb就是b的参数,optstring为"ab:cde"。
getopt返回argv中的下一个选项,外部变量optind被置为下一个要
被处理的argv数组下标,初始化为1;当遇到不能解释的选项时,会
向标准出错提示?,这个可以设置外部变量opterr为0来disable掉,
此时引起出错的选项被写入optopt;当遇到某个有参数的选项时,
optarg会指向该参数;当argv的parse完成,返回EOF。
这样解释很容易晕倒98,还是给个感性认识吧,从man里头抄个例子。
The following code fragment shows how one might process the
arguments for a command that can take the mutually exclusive
options a and b, and the option o, which requires an argu-
ment:
#include <stdlib.h>
#include <stdio.h>
main (int argc, char **argv)
{
int c;
extern char *optarg;
extern int optind;
int aflg = 0;
int bflg = 0;
int errflg = 0;
char *ofile = NULL;
while ((c = getopt(argc, argv, "abo:")) != EOF)
switch (c) {
case 'a':
if (bflg)
errflg++;
else
aflg++;
break;
case 'b':
if (aflg)
errflg++;
else
bflg++;
break;
case 'o':
ofile = optarg;
(void)printf("ofile = %s\n", ofile);
break;
case '?':
errflg++;
}
if (errflg) {
(void)fprintf(stderr,
"usage: cmd [-a|-b] [-o <filename>] files...\n");
exit (2);
}
for ( ; optind < argc; optind++)
(void)printf("%s\n", argv[optind]);
return 0;
}
--
******************************************************
青岛啤酒,可能是世界上最好的啤酒 。。。 。。。
******************************************************
※ 修改:.xh 于 Jan 5 15:33:29 修改本文.[FROM: 202.38.248.62]
※ 来源:.华南网木棉站 bbs.gznet.edu.cn.[FROM: 202.96.190.5]
--
※ 转寄:.华南网木棉站 bbs.gznet.edu.cn.[FROM: 210.39.3.50]
--
※ 转载:·BBS 荔园晨风站 bbs.szu.edu.cn·[FROM: 210.39.3.71]
[回到开始]
[上一篇][下一篇]
荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店