Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C语言学习笔记之getopt()

在写程序的时候,我们经常需要用到命令行参数,所以今天我们看看C语言中的getopt()这个函数。将C语言梳理一下,分布在以下10个章节中:
  1. Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成长之路(十):其他高级议题
C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htm我们先看看下面这个    int main (int argc,char *argv[]) {        ......    }argc寄存了命令行参数个数(注意:包括程序名本身)
例如我们运行 ./ppyy.sh          ok              ko              pp            pe                                |              |              |            |            |对应的关系是: argv[0]    argv[1]      argv[2]        argv[3]    argv[4]但是光这么用,我们是觉得不够的,记不记得我们在命令行经常使用ps -ef这样的命令,-ef就是命令行选项,它就像开关一样。为了能具备命令行选项这样的功能,我们今天来看看getopt()这个函数。首先,我们来看看一段程序<注:这段源程序来自head first>#include <stdio.h>
#include <unistd.h>          //getopt()在unistd.h这个头文件中提供int main(int argc,char *argv[]){
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;    while ((ch = getopt(argc,argv,"d:t")) != EOF ){
        switch (ch){
            case "d":
                delivery = optarg;
                break;
            case "t":
                thick = 1;
                break;
            default:
                fprintf(stderr,"Unknown option:"%s" ",optarg);            return 1;
        }    }    argc -= optind;
    argv += optind;    if (thick)
        puts("Thick crust.");    if (delivery[0])
        printf("To be delivered %s. ",delivery);    puts("Ingredients:");
    for (count=0;count<argc;count++)
        puts(argv[count]);
   
    return 0;
}更多详情见请继续阅读下一页的精彩内容: http://www.linuxidc.com/Linux/2014-06/103376p2.htm