【问题标题】:How to modify LastAccess time attribute of a file如何修改文件的 LastAccess 时间属性
【发布时间】:2020-05-09 18:04:17
【问题描述】:

我已经实现了以下功能,它将文件的 LastAccess 时间更改为当前系统的最新时间,但是,我希望它将 LastAccess 时间更改为自定义时间。例如,我给函数一个像 1994-04-04 这样的时间,然后它将 LastAccess 时间更改为那个时间。

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, FILE_WRITE_ATTRIBUTES, 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, &ft_FileTime, &ft_FileTime, &ft_FileTime))
    {
        CloseHandle(h_File);
        return true;
    }
    else
    {
        return false;
    }
    CloseHandle(h_File);
}

我应该如何修改上面的代码来达到目的?

【问题讨论】:

    标签: c++ c winapi


    【解决方案1】:

    使用SystemTimeToFileTime()function 将您请求的日期转换为可以传递给SetFileTime() 函数的正确格式。

    【讨论】:

      【解决方案2】:

      我稍微修改了您的代码以实现目标。如果你想改变文件的 LastAccess,你只需要设置这个值,其他参数设置为 NULL。

      #include <tchar.h>
      #include <windows.h>
      #include <stdio.h>
      
      BOOL SetFileToCurrentTime(LPCTSTR lpFileName) {
          HANDLE hFile;
          FILETIME ft;
          SYSTEMTIME st;
          BOOL bResult = FALSE;
          DWORD dwLastErr = ERROR_SUCCESS;
      
          hFile = CreateFile(lpFileName, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
          if (hFile == INVALID_HANDLE_VALUE) {
              // Cannot open this file
              return FALSE;
          }
      
          GetSystemTime(&st); // Gets the current system time
          SystemTimeToFileTime(&st, &ft); // Converts the current system time to file time format
      
          // set new LastAccess Time
          if (!(bResult = SetFileTime(hFile, NULL, &ft, NULL))) {
              dwLastErr = GetLastError();
          }
      
          CloseHandle(hFile);
          SetLastError(dwLastErr);
          return bResult;
      }
      
      int _tmain(int argc, _TCHAR *argv[]) {
          if (argc == 2) {
              if (SetFileToCurrentTime(argv[1])) {
                  printf("Success\n");
              } else {
                  printf("Failed! Last Error = %d\n", GetLastError());
              }
          }
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-23
        • 2015-04-04
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 2017-09-17
        相关资源
        最近更新 更多