扫码加入

  • 正文
  • 相关推荐
申请入驻 产业图谱

飞凌嵌入式ElfBoard-文件的时间属性之utime

2025/12/22
438
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

设置文件的访问时间和修改时间(秒级别)。

1.头文件

#include <sys/types.h>

#include <utime.h>

2.函数原型

int utime(const char *filename, const struct utimbuf *times);

3.参数

filename:指向文件路径名的指针,指定要修改时间的文件。如果文件路径无效或者文件不存在,utime() 会返回错误。

times:指向 struct utimbuf 结构体的指针,该结构体包含两个字段,用于指定新的访问时间和修改时间。

这里介绍一下struct utimbuf结构体:

struct utimbuf {

time_t actime;       /* 最后访问时间access time */

time_t modtime;      /* 最后修改时间modification time */

};

4.返回值

成功返回 0 ,失败返回-1,并且会返回错误原因。

5.示例:(使用utime修改文件访问时间)

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <utime.h>

#include <errno.h>

#include <string.h>

#include <time.h>

void update_file_time(const char *filename);

int main(){

const char *filename = "file_utime.txt";

int res = 0;

struct stat statbuf;

printf("File name: %sn", filename);

if (stat(filename, &statbuf) == -1) {

if (errno == ENOENT) {

fprintf(stderr,"File does not exist: %sn", filename);

} else {

perror("stat");

}

return EXIT_FAILURE;

}

update_file_time(filename);

return EXIT_SUCCESS;

}

void update_file_time(const char *filename) {

struct utimbuf new_times;

new_times.actime = time(NULL);

new_times.modtime = time(NULL);

if (utime(filename, &new_times) == -1) {

perror("utime");

exit(EXIT_FAILURE);

}

printf("File time updated successfully.n");

}

先使用stat命令查看一下file_utime.txt时间戳:

$ stat file_utime.txt

File: file_utime.txt

Size: 0          Blocks: 0          IO Block: 4096   regular empty file

Device: 803h/2051d Inode: 5242954     Links: 1

Access: (0644/-rw-r--r--)  Uid: ( 1000/     elf)   Gid: ( 1000/ elf)

Access: 2024-09-10 20:46:17.894084787 +0800

Modify: 2024-09-10 14:03:28.000000000 +0800

Change: 2024-09-10 14:03:28.393749310 +0800

Birth: 2024-09-10 14:00:57.882938108 +0800

运行utime_test命令,修改时间属性:

File name: file_utime.txt

File time updated successfully.

修改时间属性后再使用stat命令查看时间戳的变化:

$ stat file_utime.txt

File: file_utime.txt

Size: 0          Blocks: 0          IO Block: 4096   regular empty file

Device: 803h/2051d Inode: 5242954     Links: 1

Access: (0644/-rw-r--r--)  Uid: ( 1000/     elf)   Gid: ( 1000/ forlinx)

Access: 2024-11-06 21:11:21.000000000 +0800

Modify: 2024-11-06 21:11:21.000000000 +0800

Change: 2024-11-06 21:11:21.526051882 +0800

Birth: 2024-09-10 14:00:57.882938108 +0800

执行完utime_test命令后,可以看到文件的访问时间(Access time)和文件修改时间(Modification time)发生了变化,改成系统当前时间了。我们并没有修改文件状态更改时间(Change time),然而它也跟着修改了,这是一种系统机制,在ctime中,记录着文件最后一次修改的时间,对于文件的任何修改包括时间属性的更新,都会更新ctime的时间。

相关推荐