首页 > 解决方案 > 将文件的时间戳设置为自定义时间

问题描述

我想将文件的时间戳更改为自定义日期,我发现以下代码必须将文件的时间戳更改为当前时间,但是它不起作用。如何实现一个函数,它可以将文件的时间戳更改为自定义时间(由用户指定)。

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;
}

标签: cwindows

解决方案


我发现以下代码必须将文件的时间戳更改为当前时间,但它不起作用

我不知道出了什么问题,我没有要检查的 Windows 编译器,但这里有一些可能性。

  • SystemTimeToFileTime检查和的返回值CreateFile
  • 用于GetLastError找出他们失败的原因。
  • l_c_Path没有在路径和文件名之间放置路径分隔符。如果调用者不提供一个路径将是不正确的。打印出来l_c_Path

strcpy与其使用and ,不如strlcat考虑使用_makepath_s来连接路径。

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.


推荐阅读