_Windows上的utime()未在C程序中的指定时间内工作
_Windows上的utime()未在C程序中的指定时间内工作,c,windows,winapi,time,C,Windows,Winapi,Time,\u utime使用NULL作为时间参数正在更新给定文件的修改时间,但当我将时间设置为示例中所示的其他值时,它不起作用,并将错误设置为“无效参数”,请告诉我如何使用它 下面是我想让它工作的示例程序 #include <stdio.h> #include <errno.h> #include <warning.h>> #include <time.h> #include <sys/utime.h> #include <sys/
\u utime
使用NULL作为时间参数正在更新给定文件的修改时间,但当我将时间设置为示例中所示的其他值时,它不起作用,并将错误设置为“无效参数”,请告诉我如何使用它
下面是我想让它工作的示例程序
#include <stdio.h>
#include <errno.h>
#include <warning.h>>
#include <time.h>
#include <sys/utime.h>
#include <sys/types.h>
void main (void) {
struct _utimbuf updatedtime;
char *file_path = "file_name.txt";
int ret;
// here _utime update the modification time to the current time.
ret = _utime(file_path, NULL);
if(ret == -1)
printf("ret: %d \t GetLastError: %d \t strerror: %s\n", ret, errno, strerror(errno));
updatedtime.modtime = time(0) - 100000;
// here, _utime has no effect on the time.
ret = _utime(file_path, &updatedtime);
if(ret == -1)
printf("ret: %d \t GetLastError: %d \t strerror: %s\n", ret, errno, strerror(errno));
}
#包括
#包括
#包括>
#包括
#包括
#包括
无效主(无效){
结构_utimbufupdatedtime;
char*file\u path=“file\u name.txt”;
int ret;
//此处_utime将修改时间更新为当前时间。
ret=_utime(文件路径,NULL);
如果(ret==-1)
printf(“ret:%d\t GetLastError:%d\t strerror:%s\n”,ret,errno,strerror(errno));
updatedtime.modtime=时间(0)-100000;
//在这里,使用时间对时间没有影响。
ret=_utime(文件路径和更新时间);
如果(ret==-1)
printf(“ret:%d\t GetLastError:%d\t strerror:%s\n”,ret,errno,strerror(errno));
}
如中所述,对于使用_utime()更改文件修改时间,我们需要在结构的两个字段中提供有效值_utimbuf,在问题中给出的示例中,它只是更改修改时间,而访问时间是无效值
以下代码按预期工作
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/utime.h>
#include <sys/types.h>
void main (void) {
struct _utimbuf updatedtime;
char *file_path = "C:\\Users\\test_dir\\file_name.txt";
char sys_cmd[100];
int ret;
sprintf(sys_cmd, "dir %s", file_path);
ret = _utime(file_path, NULL);
if(ret == -1)
printf("GetLastError: %d \t strerror: %s\n", errno, strerror(errno));
updatedtime.modtime = time(0) - 100000;
updatedtime.actime = time(0);
system(sys_cmd);
ret = _utime(file_path, &updatedtime);
if(ret == -1)
printf("GetLastError: %d \t strerror: %s\n", errno, strerror(errno));
system(sys_cmd);
}
您尝试过吗?
mtime
中的代码未在您包含的代码段中定义。@Mgetz,是的,我刚才尝试过,我发现要使用_utime()更改文件修改时间,我们需要在结构的两个字段中都提供有效值_utimbuf,我只是更改了修改时间,访问时间是一个无效值。@not_a_real_然后将其作为answer@ryyker谢谢你指出,我已经修改了这个例子。我很高兴你得到了你的解决方案,谢谢你的分享,如果您能将它们标记为答案,我将不胜感激,这将对其他社区有益。
Volume in drive C has no label.
Volume Serial Number is 10FD-414D
Directory of C:\Users\test_dir
09-08-2020 15:24 158 file_name.txt
1 File(s) 158 bytes
0 Dir(s) 59,508,273,152 bytes free
Volume in drive C has no label.
Volume Serial Number is 10FD-414D
Directory of C:\Users\test_dir
10-08-2020 19:11 158 file_name.txt
1 File(s) 158 bytes
0 Dir(s) 59,508,273,152 bytes free