#include <unistd.h>
int getopt(int argc, char * const argv[],const char *optstring); //获取命令行参数
extern char *optarg; //参数选项(全局变量)
extern int optind, opterr, optopt; (全局变量)
命令行解析示例:optget.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#define STRSIZE 1024
#define FMTSIZE 1024
int main(int argc, char **argv)
{
time_t currentTime;
struct tm *tmRes;
int c;
char strTime[STRSIZE];
char strOpt[FMTSIZE] = {};
FILE *fp = stdout;
currentTime = time(NULL); //获取当前时间戳
if(currentTime == ((time_t) -1))
{
perror("time()");
exit(1);
}
tmRes = localtime(¤tTime); //将时间戳转为时间结构体
if(tmRes ==NULL)
{
perror("localtime()");
exit(1);
}
while(1)
{
c = getopt(argc,argv,"-y:mdH:MS"); //循环读取argv参数与要解析的对比 “X:"表示命令包含参数 头包含 "- "表示非命令传参
if(c<0)
break;
switch(c) //命令解析
{
case 1: //头包含 "- "时
fp = fopen(argv[optind-1],"w"); //解析optind-1
if(fp == NULL)
{
perror("fopen()");
fp == stdout;
}
break;
case 'y':
if(strcmp(optarg,"2")==0)
strncat(strOpt,"%y ",FMTSIZE);
else if(strcmp(optarg,"4")==0)
strncat(strOpt,"%Y ",FMTSIZE);
else
fprintf(stderr,"invalid arg of y\n");
break;
case 'm':
strncat(strOpt,"%m ",FMTSIZE);
break;
case 'd':
strncat(strOpt,"%d ",FMTSIZE);
break;
case 'H':
if(strcmp(optarg,"12") ==0)
strncat(strOpt,"%I(%p) ",FMTSIZE);
else if(strcmp(optarg,"24") ==0)
strncat(strOpt,"%H ",FMTSIZE);
else
fprintf(stderr,"invalid arg of H\n");
break;
case 'M':
strncat(strOpt,"%M ",FMTSIZE);
break;
case 'S':
strncat(strOpt,"%S ",FMTSIZE);
break;
default:
break;
}
}
strncat(strOpt,"\n",FMTSIZE);
strftime(strTime,STRSIZE,strOpt,tmRes); //格式化输出时间
fputs(strTime,fp);
if(fp !=stdout)
fclose(fp); //关闭文件
exit(0);
}