將檔案時間變更為目前時間

下列範例會使用 SetFileTime 函式,將檔案的最後寫入時間設定為目前的系統時間。

NTFS 檔案系統會以 UTC 格式儲存時間值,因此不會受到時區變更或日光節約時間的影響。 FAT 檔案系統會根據電腦的當地時間儲存時間值。

檔案必須使用 createFile 函式開啟,才能使用 FILE_WRITE_ATTRIBUTES 存取。

#include <windows.h>

// SetFileToCurrentTime - sets last write time to current system time
// Return value - TRUE if successful, FALSE otherwise
// hFile  - must be a valid file handle

BOOL SetFileToCurrentTime(HANDLE hFile)
{
    FILETIME ft;
    SYSTEMTIME st;
    BOOL f;

    GetSystemTime(&st);              // Gets the current system time
    SystemTimeToFileTime(&st, &ft);  // Converts the current system time to file time format
    f = SetFileTime(hFile,           // Sets last-write time of the file 
        (LPFILETIME) NULL,           // to the converted current system time 
        (LPFILETIME) NULL, 
        &ft);    

    return f;
}