▚ 01 程序介绍
EXE -w width -h height
▚ 02 源码示例
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct
{
int height;
int width;
}s_param;
void WarnMsg(const char * cmd)
{
printf("\n**********************************\n");
printf("%s [-w width>0 -h height>0 ]\n",cmd);
printf("**********************************\n\n");
}
int GetParam(int argc, char *argv[], s_param *param)
{
int opt,tmp;
int flag=0;
if(!argv || !param)
{
printf("Input Error.\n");
return -1;
}
memset(param, 0, sizeof(s_param));
while(1)
{
opt = getopt(argc, argv, "w:h:");
if(opt == -1)
{
break;
}
switch (opt)
{
case 'w':
if(optarg == NULL)
{
printf("Need paramter for %c\n", optarg);
WarnMsg(argv[0]);
return -1;
}
tmp = atoi(optarg);
if(tmp <= 0)
++flag;
param->width = tmp;
break;
case 'h':
if(optarg == NULL)
{
printf("Need paramter for %c\n", optarg);
WarnMsg(argv[0]);
return -1;
}
tmp = atoi(optarg);
if(tmp <= 0)
++flag;
param->height = tmp;
break;
default:
break;
}
}
if(flag > 0)
return -1;
return 0;
}
int PrintParam(s_param *param)
{
if(param == NULL)
return -1;
printf("Parameters:\n");
printf("\t width = %d\n", param->width);
printf("\t height = %d\n", param->height);
return 0;
}
int main(int argc, char *argv[])
{
int ret, area;
s_param param;
ret = GetParam(argc, argv, ¶m);
PrintParam(¶m);
if(ret == 0)
printf("\n area = %d\n", param.width * param.height);
else
{
printf("\n parameters error!\n");
WarnMsg(argv[0]);
}
return 0;
}
▚ 03 运行结果