C程序起点main函数
C程序起点main函数
main
c语言中main函数接收两个参数int argc, char* argv[]
int main(int argc, char* argv[]);
int main(int argc, char** argv);
如上,argc代表参数的数量,argv但是参数字符串指针数组
./program -i 192.168.0.1 -p 2000
此时共有五个参数,
argv[0] --> ./program
argv[1] --> -i
argv[2] --> 192.168.0.1
argv[3] --> -p
argv[4] --> 2000
短选项接收
那么我们怎么去接收这些参数并去识别,那么就要用到getopt.h的getopt()函数了。
int getopt(int argc, char** argv, char* optstring);
第一个参数、第二个参数对应即可,第三个参数接收的是选项如"i:p:",i、p代表选项,:代表其后接收一个参数。每个选项例如"-i"这个函数会直接过滤掉-,每次获取时会自动将:后的参数传入到optarg,下次获取会直接跳到下一个选项。此函数的返回值为选项'i'的ASCII码值。optind表示的是经过了多少个元素(包括参数和选项)。
实例
int main(int argc, int char){
// 判断参数
if(argc < 5) return -1;
int ret = 0;
char* ip =NULL;
int port = 0;
// i,p表示两个命令,:表示需要一个参数
while ((ret = getopt(argc, argv, "i:p:")) != EOF){
// printf("char is %c\n", ret);
switch (ret)
{
case 'i':
// printf("optarg: %s\n", optarg);
ip = optarg;
break;
case 'p':
// printf("optarg: %s\n", optarg);
port = atoi(optarg);
break;
default:
break;
}
}
printf("ip: %s, port: %d\n", ip, port);
return 0;
}
长选项接收
如果有长命令的输入需求的话,可以使用getopt_long函数和getopt_long_only函数
int getopt_long (int argc, char ** argv, const char *shortopts, const struct option *longopts, int *longind);
int getopt_long_only (int argc, char ** argv, const char *shortopts, const struct option *longopts, int *longind);
这两个函数的区别是后者会将-和--都解释为长命令,前者只会认为-是短命令。值得一提的是,这两个函数的返回值都是结构体中定义的长命令的返回值。longid指向的是每一个选项的位置。
长选项结构体
struct option {
char* name; // 选项名字
int has_args; // 是否有参,有三个宏定义
int* flag; // 为0代表,返回值是常量,如果非0,返回值是一个变量
int val; // 返回值
};
实例
#include <getopt.h>
#include <stdio.h>
// ./test --dmac 00:0c:6e:bb:bc:a7 --sip 192.168.3.105 --dip 192.168.3.102 --sport 8000 --dport 2000
int main(int argc, char *argv[])
{
if (argc < 11)
{
return -1;
}
while (1)
{
int long_index = 0;
static struct option long_options[] = {
{"dmac", required_argument, 0, 0},
{"sip", required_argument, 0, 1},
{"dip", required_argument, 0, 2},
{"sport", required_argument, 0, 3},
{"dport", required_argument, 0, 4},
{0, 0, 0, 0}};
int c = 0;
c = getopt_long_only(argc, argv, "", long_options, &long_index);
if (c == -1)
{
break;
}
switch (c)
{
case 0:
printf("option %s", long_options[long_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case 1:
printf("option %s", long_options[long_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case 2:
printf("option %s", long_options[long_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case 3:
printf("option %s", long_options[long_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case 4:
printf("option %s", long_options[long_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
default:
break;
}
}
}

浙公网安备 33010602011771号