1.getopt
#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
optarg 如果一个选项带了参数,当解析到这个选项的时候,这个全局变量会自动指向这个参数
optind 记录读到了哪个下标
RETURN VALUE
If an option was successfully found,
then getopt() returns the option character.
If all command-line options have been parsed,
then getopt() returns -1.
If getopt() encounters an option character that
was not in optstring, then '?' is returned
If the first character of optstring is '-', then each
nonoption argv-element is handled as if it were the argument of
an option with character code 1.
(This is used by programs that were written to expect options and
other argv-elements in any order and that care about the
ordering of the two.)
如果格式的第一个字符是’-'的话,那么里面就包含一个非选项,匹配到了 会返回1
一个Demo
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define MAXSIZE 1024
int main(int argc, char **argv)
{
//这个文件描述符是记录向终端写入还是文件写入
FILE *fp = stdout;
time_t Int64Time;
struct tm *pTime;
//存储时间
char TimeBuf[MAXSIZE];
//存储转化格式
char Format[MAXSIZE];
//存储返回值
int res;
Format[0] = '\0';
time(&Int64Time);
pTime = localtime(&Int64Time);
while(1)
{
res = getopt(argc, argv, "-H:MSy:md");
if(res < 0)
break;
switch(res)
{
case 1:
{
fp = fopen(argv[optind-1] ,"w");
if(NULL == fp)
{
perror("fopen()");
fp = stdout;
}
}
break;
case 'H':
{
if(0 == strcmp("24", optarg))
strncat(Format, "%H ", MAXSIZE);
else if(0 == strcmp("12", optarg))
strncat(Format, "%I(%P) ", MAXSIZE);
else
fprintf(stderr, "Illegal argv\n");
}
break;
case 'M':
strncat(Format, "%M ", MAXSIZE);
break;
case 'S':
strncat(Format, "%S ", MAXSIZE);
break;
case 'y':
{
if(0 == strcmp("2", optarg))
strncat(Format, "%y ", MAXSIZE);
if(0 == strcmp("4", optarg))
strncat(Format, "%Y ", MAXSIZE);
else
fprintf(stderr, "Illegal argv\n");
}
break;
case 'm':
strncat(Format, "%m ", MAXSIZE);
break;
case 'd':
strncat(Format, "%d ", MAXSIZE);
break;
default:
break;
}
}
//根据格式 来生成对应需要的时间格式
strftime(TimeBuf, MAXSIZE, Format, pTime);
//输出到fp
fputs(TimeBuf, fp);
puts("");
//忘记加close了
return 0;
}
-H:MSy:md
①- 这个杠代表要传入的参数里面有非选项,在这个例子中这个非选项是个文件,有非选项写入文件,没有写入终端
②:这个冒号代表他是有参数的选项 这个例子中的y和H 都带了参数