手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux中getopt函数用法

[日期:2013-05-01] 来源:Linux社区  作者:xuzhezhaozhao [字体:大 中 小]

假设编译好的可执行文件名为test, test有3个有效参数-n, -b, -t, 其中-n, -t后不接参数, -b后一定要接参数, -o后接可选参数.

# ./test -x -y -z                <------ 无效参数, 会打印错误信息, 并返回字符'?'

输出:

./getopt: invalid option -- 'x'
opt = ?, optarg = (null), optind = 2, argv[2] = -y
./getopt: invalid option -- 'y'
opt = ?, optarg = (null), optind = 3, argv[3] = -z
./getopt: invalid option -- 'z'
opt = ?, optarg = (null), optind = 4, argv[4] = (null)

# ./test -n -b xzz -t

opt = n, optarg = (null), optind = 2, argv[2] = -b
opt = b, optarg = xzz, optind = 4, argv[4] = -t                <----------- optarg 指向选项元素的参数, 并且optind跳过了该参数, 直接指向了-t参数
opt = t, optarg = (null), optind = 5, argv[5] = (null)

# ./test -n -bxzz -t                            <------------- 也可将选项参数与其接的参数写在一起

opt = n, optarg = (null), optind = 2, argv[2] = -bxzz
opt = b, optarg = xzz, optind = 3, argv[3] = -t                <----------- optind 同样将指向下一个参数-t
opt = t, optarg = (null), optind = 4, argv[4] = (null)

# ./test -b -t

opt = b, optarg = -t, optind = 3, argv[3] = (null)      <----------- 将-t当成了选项元素-b的参数, 之后就不再解析-t, optind为3

# ./test -t -b <---- -b缺少参数

opt = t, optarg = (null), optind = 2, argv[2] = -b
./getopt: option requires an argument -- 'b'
opt = ?, optarg = (null), optind = 3, argv[3] = (null)

# ./test -t a -b xzz <------- 命令行中有一个无用参数 a, 解析时被忽略了, 因为-t不需要接参数

opt = t, optarg = (null), optind = 2, argv[2] = a
opt = b, optarg = xzz, optind = 5, argv[5] = (null)

# ./test -ntb xzz <--------- 还可以把参数连在一起写

opt = n, optarg = (null), optind = 1, argv[1] = -ntb
opt = t, optarg = (null), optind = 1, argv[1] = -ntb
opt = b, optarg = xzz, optind = 3, argv[3] = (null)

# ./test -t -o -b xzz <----- -o选项不接参数

opt = t, optarg = (null), optind = 2, argv[2] = -o
opt = o, optarg = (null), optind = 3, argv[3] = -b
opt = b, optarg = xzz, optind = 5, argv[5] = (null)

# ./test -t -o 10 -b xzz <------ -o选项接参数10

opt = t, optarg = (null), optind = 2, argv[2] = -o
opt = o, optarg = (null), optind = 3, argv[3] = 10          <------------------ <strong><span style="color: rgb(255, 0, 0);">可以看到10并没有保存在optarg中</span></strong>
opt = b, optarg = xzz, optind = 6, argv[6] = (null)        <-----------------  而-b的参数则保存在optarg中了

linux
相关资讯       Linux函数  Linux getopt 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款