我想将文件的时间戳记更改为自定义日期,我发现以下代码必须将文件的时间戳记更改为当前时间,但是它不起作用。如何实现一个功能,该功能可以将文件的时间戳更改为自定义时间(由用户指定)。
bool SetFileToCurrentTime(const char* arg_path, const char* arg_file_name)
{
HANDLE h_File;
FILETIME ft_FileTime;
SYSTEMTIME st_SystemTime;
char l_c_Path[MAX_PATH];
strcpy(l_c_Path, arg_path);
strcat(l_c_Path, arg_file_name);
h_File = CreateFile(l_c_Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
GetSystemTime(&st_SystemTime); // Gets the current system time
SystemTimeToFileTime(&st_SystemTime, &ft_FileTime); // Converts the current system time to file time format
if (SetFileTime(h_File, (LPFILETIME)NULL, (LPFILETIME)NULL, &ft_FileTime))
return true;
else
return false;
}
答案 0 :(得分:2)
我发现以下代码必须将文件的时间戳更改为当前时间,但无法正常工作
我不知道出了什么问题,我没有Windows编译器要检查,但是有一些可能。
SystemTimeToFileTime
和CreateFile
的返回值。GetLastError
找出失败的原因。l_c_Path
不在路径和文件名之间放置路径分隔符。如果呼叫者不提供一个,则路径将不正确。打印出l_c_Path
。考虑使用_makepath_s
连接路径,而不是使用strcpy
和strlcat
。
char l_c_Path[_MAX_PATH];
errno_t errorCode = _makepath_s(l_c_Path, _MAX_PATH, NULL, arg_path, arg_file_name, NULL);
if( errorCode ) {
// check the errorCode
}
如何实现一个功能,该功能可以将文件的时间戳更改为自定义时间(由用户指定)。
让调用者传递GetSystemTime
,而不是调用SystemTimeToFileTime
并用FILETIME
进行转换。