|
设置文件的访问时间和修改时间(微秒级别) 1.头文件 #include <sys/time.h> 2.函数原型 int utimes(const char *filename, const struct timeval times[2]); 3.参数 filrname:要修改时间的文件名。 times:是一个包含两个 struct timeval 的数组,第一个表示访问时间,第二个表示修改时间。如果设置为 NULL,utimes 会使用当前时间。 下面介绍一下struct timeval结构体: struct timeval { long tv_sec; /* 秒seconds */ long tv_usec; /* 微秒microseconds */ }; 4.返回值 成功返回0,失败返回-1,并设置errno以指示返回错误类型 。 5.示例:(使用utimes修改文件访问时间) #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <utime.h> #include <errno.h> #include <string.h> #include <time.h> #include <sys/time.h> void update_file_time(const char *filename); int main(){ const char *filename = "file_utimes.txt"; int res = 0; struct stat statbuf; printf("File name: %s\n", filename); if (stat(filename, &statbuf) == -1) { if (errno == ENOENT) { fprintf(stderr,"File does not exist: %s\n", filename); } else { perror("stat"); } return EXIT_FAILURE; } update_file_time(filename); return EXIT_SUCCESS; } void update_file_time(const char *filename){ struct timeval times[2]; int i; for (i=0; i<2; i++) { times.tv_sec = time(NULL); times.tv_usec = 666; } if (utimes(filename, times) == -1) { perror("utimes"); exit(EXIT_FAILURE); } printf("File time updated successfully.\n"); } |
|