您的位置:首页 > 编程语言

UNIX环境高级编程读书笔记(六)—时间和日期 (1)

2008-08-19 19:00 651 查看
一.文件的时间[/b]
对每个文件保存三个时间字段,它们是:





1.

名称::utime
功能:修改文件的存取和修改时间
头文件:#include <utime.h>
#include <sys/types.h>
函数原形: int utime(const char *filename,const struct utimbuf buf);
参数:pathname 文件名
buf 文件时间信息
返回值:若成功则返回0,若出错则返回-1
此函数所使用的结构是:
struct utimbuf{
time_t actime; 文件数据的最后存取时间
time_t modtime; 文件数据的最后修改时间
}

二.系统的时间[/b]
[/b]



2.

名称::time
功能:get time in seconds
头文件:#include <time.h>
函数原形: time_t time(time_t *calptr);
参数:calptr 时间值
返回值:若成功则返回时间值,若出错则返回-1
time返回的是计算自国家标准时间公元1970年1月1日00:00:00以来经过的秒数。时间值总是作为时间值返回,如果参数不为空则时间值也存放在由calptr所指向的单元内。
下面的程序可以实现touch命令的部分功能,可以把文件的最后存储时间和最后修改时间改为执行命令时的系统时间。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utime.h>

int main(int argc,char *argv[])
{
int i;
struct utimbuf timebuf;

for(i=1;i<argc;i++)

timebuf.actime=time();
timebuf.actime=time();
if(utime(argv[i],&timebuf)<0)
perror(“error”);
exit(0);
}
}
3.

名称::gettimeofday/settimeofday
功能:get/set time
头文件:#include <sys/time.h>
函数原形: int gettimeofday(struct timeval *tv,struct timezone *tz);
int settimofday(const struct timeval *tv,const struct timezone *tz);
参数:tv
tz
返回值:总是返回0
与time函数相比,gettimeofday提供了更高的分辨率,最高为微秒级,这对某些要求实时性较高的程序来说是很重要的。
gettimeoffday函数将当前时间存放在tp指向的timeval结构中,而该结构存储秒和微妙。tz的唯一合法值是NULL,其他值则将产生不确定结构。某些平台支持用tz说明时区,但这完全依现实而定。
struct timeval{
time_t tv_sec;
long tv_usec;
};


文章转自:http://blog.chinaunix.net/u1/59291/showart.php?id=538554
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: