免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2780 | 回复: 4
打印 上一主题 下一主题

getopt 问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-24 15:44 |只看该作者 |倒序浏览
char *svalue=NULL;


while((opt=getopt(argc,argv," :ls: ")!=-1))


.
.
.

case 's':
         svalue=optarg;
         break;


RUN:

./a -s file1


1.问题: 如果我想-s接收的是多个不定的参数请问怎么改呢?
如:  -s file1 file2 或 -s file1 file2 file3

2.在书上看       opt=getopt(argc,argv," :ls::k ")!=-1
s后两个"::"表示接收两个参数?还是两个以上的参数呢?

论坛徽章:
0
2 [报告]
发表于 2006-08-24 16:10 |只看该作者
特走网吧发问的.......非常急啊,请帮帮我.

论坛徽章:
0
3 [报告]
发表于 2006-08-24 16:30 |只看该作者
getopt(分析命令行参数)  
相关函数  

表头文件  #include<unistd.h>

定义函数  int getopt(int argc,char * const argv[ ],const char * optstring);

函数说明  getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。

返回值  如果找到符合的参数则返回此参数字母,如果参数不包含在参数optstring 的选项字母则返回“?”字符,分析结束则返回-1。

范例  #include<stdio.h>
#include<unistd.h>
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
switch(ch)
{
case ‘a’:
printf(“option a:’%s’\n”,optarg);
break;
case ‘b’:
printf(“option b :b\n”);
break;
default:
printf(“other option :%c\n”,ch);
}
printf(“optopt +%c\n”,optopt);
}

执行  $./getopt –b
option b:b
$./getopt –c
other option:c
$./getopt –a
other option
$./getopt –a12345
option a:’12345’

论坛徽章:
0
4 [报告]
发表于 2006-08-24 16:43 |只看该作者
这个我知道啊....但是如果接收不定数目的参数呢?如:

-s file1 file2 或 -s file1 file2 file3

论坛徽章:
0
5 [报告]
发表于 2006-08-25 02:07 |只看该作者
unistd里有个 optind 变量,每次getopt后,这个索引指向argv里当前分析的字符串的下一个索引,因此
argv[optind]就能得到下个字符串,通过判断是否以 '-'开头就可。下面是个测试程序

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. int main(int argc, char* argv[])
  4. {
  5.     int tmp = 4;
  6.    
  7.     while( (tmp = getopt(argc, argv, "abck")) != -1  )
  8.     {
  9.            
  10.            printf("-%c\t", tmp);
  11.            int opt = optind ;
  12.            while( opt < argc )
  13.            {
  14.                   if ( argv[opt][0] != '-' )
  15.                   {
  16.                        printf("%s\t", argv[opt]);
  17.                        opt ++;
  18.                   }
  19.                   else
  20.                       break;
  21.            }
  22.            printf("\n");
  23.     }
  24.     getchar();
  25. }
复制代码

[ 本帖最后由 harly 于 2006-8-25 02:12 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP