博客首页 注册 建议与交流 排行榜 加入友情链接         宝宝相册的专门空间
推荐 投诉 搜索: 帮助

愿逝者安息 让生者前行 深切哀悼5.12遇难同胞

愿逝者安息 让生者前行 深切哀悼5.12遇难同胞
creatory.cublog.cn


Unix Advanced Programming Practise4
命令行参数处理
<unistd.h>
外部值
extern char *optarg; //指向要处理选项的参数,如-f uclinux.tar.gz则optarg

包含uclinux.tar.gz的C串
extern int optind; //初始化为1,指向要处理的下一个argv[]的值
extern int optopt;
extern int optind;
extern int opterr;
int getopt(int argc,char *const argv[],const char *optstring);
参数说明:
argc参数个数,argv参数列表,optstring包含的选项符
定义optstring参数
支持-c -v -f XXX
可这样定义:
static char optstring[]="cvf:";
其中:指定-f要求一个参数
例:
#include <stdio.h>
#include <unistd.h>
int main(int argc,char **argv)
{
int optch;
static char optstring[]="cvf:";
while((optch=getopt(argc,argv,optstring))!=-1)
switch(optch)
{
case 'c':
puts("-c ok\n");
break;
case 'v':
puts("-v ok\n");
break;
case 'f':
printf("-f %s ok\n",optarg);
break;
}
for(;optind<argc;++optind)
printf("argv[%d]=%s\n",optind,argv[optind]);
return 0;
}
转换函数
<stdlib.h>
int atoi(const char *nptr); //ASCII to Int
long atol(const char *nptr); //ASCII to Long
double atof(const char *nptr); //ASCII to float
例:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char buf[10];
int i;
long j;
strcpy(buf,"1024");
i=atoi(buf);
strcpy(buf,"1000000000");
j=atol(buf);
printf("String:%s = Int:%d\n",buf,i);
printf("String:%s = Long:%ld\n",buf,j);
return 0;
}
日期
获得当前日期和时间
<time.h>
time_t time(time_t *tloc);
将时间转换为串形式
char *ctime(const time_t *timep);
例:
#include <stdio.h>
#include <time.h>
int main()
{
time_t cur;
time(&cur);
printf("CurrentTime:%s\n",ctime(&cur));
return 0;
}
线程安全版本
char *ctime_r(const time_t *clock,char *buf);
修改上述程序
char buf[64];
printf("CurrentTime:%s\n",ctime(&cur,buf));
从time_t中抽取日期成份
struct tm *localtime(const time_t *timep); //按照当地时间返回日期和时间
struct tm *gmtime(const time_t *timep);//按UTC时区返回
线程安全版本
struct tm *localtime_r(const time_t *clock,struct tm *result);
struct tm *gmtime_t(const time_t *clock,struct tm *result);
struct tm
{
int tm_sec; //秒
int tm_min;  //分
int tm_hour;  //时
int tm_mday;  //天数,1-31
int tm_mon;  //月数,0-11
int tm_year;  //年
int tm_wday; //一周天数
int tm_yday; //一年天数
int tm_isdst;
};
将时期/时间转换为串
char *asctime(const struct tm *tm_ptr);
char *asctime_r(const struct tm *tm_prt,char *buf);
例:
#include <time.h>
#include <stdio.h>
#include <string.h>
int main()
{
time_t dt;
struct tm dc;
char buf[25];
time(&dt);
dc=*localtime(&dt);
strcpy(buf,asctime(&dc));
printf("CT:%s\n",buf);
return 0;
}

发表于: 2008-03-27 ,修改于: 2008-03-27 16:49,已浏览137次,有评论0条 推荐 投诉


网友评论

发表评论