貌似有些時間(合法的時間)設定不下去。保持原有檔案時間。
boolean modifyWriteTime(string path1, string path2) {
FILETIME ftCreate1, ftAccess1, ftWrite1;
FILETIME ftCreate2, ftAccess2, ftWrite2;
FILETIME ftCreate3, ftAccess3, ftWrite3;
HANDLE fh1 = CreateFile((CString)path1.c_str(), GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, 0);
if (!GetFileTime(fh1, &ftCreate1, &ftAccess1, &ftWrite1)) {
CloseHandle(fh1);
return FALSE;
}
HANDLE fh2 = CreateFile((CString)path2.c_str(), GENERIC_ALL,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); // FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_WRITE_THROUGH
if (!GetFileTime(fh2, &ftCreate2, &ftAccess2, &ftWrite2)) {
CloseHandle(fh1);
return FALSE;
}
//設定時間 引數(檔案句柄,創建時間,修改時間)
DWORD r1 = GetLastError();
//ftWrite1.dwHighDateTime = 30786615;
//ftWrite1.dwLowDateTime = 3460456960;
BOOL retModTime = SetFileTime(fh2, &ftCreate1, &ftAccess1, &ftWrite1);
DWORD r2 = GetLastError();
if (!retModTime) {
CloseHandle(fh1);
CloseHandle(fh2);
return FALSE;
}
CloseHandle(fh1);
CloseHandle(fh2);
HANDLE fh3 = CreateFile((CString)path2.c_str(), GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, 0); // FILE_FLAG_BACKUP_SEMANTICS
if (fh3 == NULL) {
return false;
}
ftWrite3.dwHighDateTime = 111;
ftWrite3.dwLowDateTime = 222;
if (!GetFileTime(fh3, &ftCreate3, &ftAccess3, &ftWrite3)) {
CloseHandle(fh3);
return FALSE;
}
CloseHandle(fh3);
return true;
}
ftWrite3取得的時間和ftWrite2一致,無法和ftWrite1一致。但是,修改ftWrite2的值(注釋掉的兩行),是可以設下去的。
沒有報錯和失敗。
懷疑是不是不能把過去的時間設定下去?
uj5u.com熱心網友回復:
MSDN 上的說明Changing a File Time to the Current Time
The following example sets the last-write time for a file to the current system time using the SetFileTime function. Note that the file must be opened with the CreateFile function using FILE_WRITE_ATTRIBUTES access.
#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 current time
SystemTimeToFileTime(&st, &ft); // converts to file time format
f = SetFileTime(hFile, // sets last-write time for file
(LPFILETIME) NULL, (LPFILETIME) NULL, &ft);
return f;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/249194.html
標籤:基礎類
