主函数main也可以接收参数。main只有这两个参数。argc表示参数(包括程序名)个数,argv是一个指针数组,其中每个指针指向一个字符串,即一个参数,因此argv[0]就是程序名,argv[1]就是第一个参数现面用两个例子来说明。
例1:将传入的依次参数列出来
#include <stdio.h>
int main(int argc, char **argv)
{
int c;
for(c = 0; c < argc; c++)
{
printf("argument %d is: %s\n",c,argv[c]);
}
return 0;
}
上面的这种通过argv数组来获取参数的方法必须将参数的顺序按照规定来填写。运行上面的例子,执行结果如下
miko@bogon:~/wordspace/study/main> ./a.out arg1 arg2 arg3 argument 0 is: ./a.out argument 1 is: arg1 argument 2 is: arg2 argument 3 is: arg3
例子2 指定选项来传递参数,参数的顺序没有规定。#include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { int opt = 0; /* opterr = 0; */ /* [1] */ while((opt = getopt(argc,argv,"ha:b:")) != -1) /*[2]*/ { switch (opt) { case 'h': printf("help option\n"); break; case 'a': printf("option a is: %s\n",optarg); break; case 'b': printf("option b\n"); break; default: printf("check your options"); return 0; break; } } return 0; }
这种方法比上面的那个例子多了选项,但是灵活了许多,参数可以只指定一部分,并且可以不 依照顺序,程序中需要的参数通过选现获得,而并不是通过传入参数的顺序。
上面例子的执行结果如下:
miko@bogon:~/wordspace/study/main> ./a.out -h -a "arg1" -b "arg2" help option option a is: arg1 option b is: arg2
如果输入没有的选项,则程序会给出提示
miko@bogon:~/wordspace/study/main> ./a.out -d ./a.out: invalid option -- 'd' check your options
在这个例子中有几点需要注意:
[1] opterr这个全局变量来标识是否提示输入了错误的选项 如果为opterr=0则标识不提示。具体参考getopt()函数.
[2]getopt()函数的第三个参数,如果指定选项后没有参数,则这个选项后不应该加“:”,如果有参数 则要加上“:”,例如上面的这个例子。“h"选项没有参数,其后不应该接“:”,而 “a“和”b“两个选项后都有参数,则都加了”:“。