#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define STRLENTH 1024
int main(int argc, char **argv)
{
int c;
char strfmt[STRLENTH]={0};
char strTm[STRLENTH]={0};
FILE* fp=stdout;
time_t currentTime;
struct tm *currentTm;
currentTime = time(NULL);
currentTm = localtime(¤tTime);
while(1)
{
c = getopt(argc, argv, "-MmSY:H:d");
if(c<=0) break;
switch(c)
{
case 1: //非选项传参
fp = fopen(argv[optind-1],"w+");
if(fp == NULL)
{
fp = stdout;
}
break;
case 'Y': //带参选项
if(strcmp(optarg, "2") ==0)
{
strncat(strfmt,"%y ",STRLENTH);
}
else if(strcmp(optarg, "4") ==0)
{
strncat(strfmt,"%Y ",STRLENTH);
}
else
{
fprintf(stderr,"Y format error\n");
}
break;
case 'm':
strncat(strfmt,"%m ",STRLENTH);
break;
case 'd':
strncat(strfmt,"%d ",STRLENTH);
break;
case 'H':
if(strcmp(optarg, "12") ==0)
{
strncat(strfmt,"%I(%P) ",STRLENTH);
}
else if(strcmp(optarg, "24") ==0)
{
strncat(strfmt,"%H ",STRLENTH);
}
else
{
fprintf(stderr,"H format error\n");
}
break;
case 'M':
strncat(strfmt,"%M ",STRLENTH);
break;
case 'S':
strncat(strfmt,"%S ",STRLENTH);
break;
default:
break;
}
}
strncat(strfmt,"\n",STRLENTH);
strftime(strTm, STRLENTH, strfmt, currentTm);
fputs(strTm, fp);
if(fp != stdout)
fclose(fp);
exit(0);
}
标签:传参,strncat,strfmt,STRLENTH,break,case,fp,命令行,getopt From: https://www.cnblogs.com/linux-learn/p/18541083