场景:
1. 有时候软件需要从其他地方下载或传输文件到本地, 因为是新建的文件,所以创建时间是当前时间, 这时候就需要修改它的创建时间和修改时间保持一致.
2. Windows的文件时间是可以修改的, 使用SetFileTime .但是要注意使用 TzSpecificLocalTimeToSystemTime 转换下时间, 不然因为时区会有误差.
TEST(test_file_attribute,GetAttribute)
{
//1.获取文件时间
//1.当然GetFileTime也可以.
WIN32_FILE_ATTRIBUTE_DATA data;
memset(&data,0,sizeof(WIN32_FILE_ATTRIBUTE_DATA));
BOOL result = GetFileAttributesEx(
L"../1.csv",
GetFileExInfoStandard,
&data);
if(result)
{
FILETIME ct = data.ftCreationTime;
FILETIME at = data.ftLastAccessTime;
FILETIME wt = data.ftLastWriteTime;
SYSTEMTIME stUTC, stLocal;
if(wt.dwHighDateTime || wt.dwLowDateTime)
{
FileTimeToSystemTime(&wt, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
// Build a string showing the date and time.
TCHAR lpszString[MAX_PATH];
DWORD dwRet = StringCchPrintf(lpszString, MAX_PATH,
TEXT("%02d/%02d/%d %02d:%02d"),
stLocal.wMonth, stLocal.wDay, stLocal.wYear,
stLocal.wHour, stLocal.wMinute);
std::wcout << L"Write Time: " << lpszString << std::endl;
}
if(at.dwHighDateTime || at.dwLowDateTime)
{
FileTimeToSystemTime(&at, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
TCHAR lpszString[MAX_PATH];
DWORD dwRet = StringCchPrintf(lpszString, MAX_PATH,
TEXT("%02d/%02d/%d %02d:%02d"),
stLocal.wMonth, stLocal.wDay, stLocal.wYear,
stLocal.wHour, stLocal.wMinute);
std::wcout << L"Access Time: " << lpszString << std::endl;
}
if(ct.dwHighDateTime || ct.dwLowDateTime)
{
FileTimeToSystemTime(&ct, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
TCHAR lpszString[MAX_PATH];
DWORD dwRet = StringCchPrintf(lpszString, MAX_PATH,
TEXT("%02d/%02d/%d %02d:%02d"),
stLocal.wMonth, stLocal.wDay, stLocal.wYear,
stLocal.wHour, stLocal.wMinute);
std::wcout << L"Create Time: " << lpszString << std::endl;
}
}
//1. 修改文件时间.
HANDLE file = CreateFile(L"../1.csv",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(file != INVALID_HANDLE_VALUE)
{
FILETIME ft;
SYSTEMTIME st,stUTC;
BOOL f;
//hour: 0-23
GetSystemTime(&st); // Gets the current system time
st.wYear = 2013;
TzSpecificLocalTimeToSystemTime(NULL,&st,&stUTC);
SystemTimeToFileTime(&stUTC, &ft); // Converts the current system time to file time format
f = SetFileTime(file, // Sets last-write time of the file
&ft,&ft, // to the converted current system time
&ft);
CloseHandle(file);
}
修改后的文件时间: