文件和目录之utime函数

一个文件的访问和修改时间可以用utime函数更改。

#include <utime.h>
int utime( const char *pathname, const struct utimbuf *times );
返回值:若成功则返回0,若出错则返回-1

此函数所使用的数据结构是:

struct utimbuf {
    time_t actime;    /* access time */
    time_t modtime;    /* modification time */
}

此结构中的两个时间值是日历时间。这是自1970年1月1日00:00:00以来国际标准时间所经过的秒数。

此函数的操作以及执行它所要求的特权取决于times参数是否是NULL。

如果times是一个空指针,则访问时间和修改时间两者都设置为当前时间。为了执行此操作必须满足下列两个条件之一:进程的有效用户ID必须等于该文件的所有者ID;或者进程对该文件必须具有写权限。

如果times是非空指针,则访问时间和修改时间被设置为times所指向结构中的值。此时,进程的有效用户ID必须等于该文件的所有者ID,或者进程必须是一个超级用户进程。对文件只有写权限是不够的。

注意,我们不能对更改状态时间st_ctime指定一个值,当调用utime函数时,此字段将被自动更新。

在某些UNIX系统版本中,touch(1)命令使用此函数。另外,标准归档程序tar(1)和cpio(1)可选地调用utime,以便将一个文件的时间设置为将它归档时保存的时间值。

程序清单4-6 utime函数实例

使用带O_TRUNC选项的open函数将文件长度截短为0,但并不更改其访问时间及修改时间。为了做到这一点,首先用stat函数得到这些时间,然后截短文件,最后再用utime函数复位这两个时间。

[root@localhost apue]# cat prog4-6.c 
#include "apue.h"
#include <fcntl.h>
#include <utime.h>

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

        for(i=1; i<argc; i++)
        {
                if(stat(argv[i], &statbuf) < 0)
                {
                        err_ret("%s: stat error", argv[i]);
                        continue;
                }
                if((fd = open(argv[i], O_RDWR | O_TRUNC)) < 0)
                {
                        err_ret("%s: open error", argv[i]);
                        continue;
                }
                close(fd);
                timebuf.actime = statbuf.st_atime;
                timebuf.modtime = statbuf.st_mtime;
                if(utime(argv[i], &timebuf) < 0)
                {
                        err_ret("%s: utime error", argv[i]);
                        continue;
                }
        }
        exit(0);
}

运行结果:

[root@localhost apue]# ls -l file.hole
-rw-r--r-- 1 root root 0 12-30 00:38 file.hole
[root@localhost apue]# date
2014年 01月 03日 星期五 16:34:48 PST
[root@localhost apue]# ./prog4-6 file.hole
[root@localhost apue]# ls -l file.hole
-rw-r--r-- 1 root root 0 12-30 00:38 file.hole
[root@localhost apue]# ls -lu file.hole
-rw-r--r-- 1 root root 0 12-30 00:38 file.hole
[root@localhost apue]# ls -lc file.hole
-rw-r--r-- 1 root root 0 01-03 16:34 file.hole

正如我们所预见的一样,最后修改时间和最后访问时间未变。但是更改状态时间则更改为程序运行时的时间。

本篇博文内容摘自《UNIX环境高级编程》(第二版),仅作个人学习记录所用。关于本书可参考:http://www.apuebook.com/

原文地址:https://www.cnblogs.com/nufangrensheng/p/3503941.html