How to set a file's last access time on Win32 in C++ using FILETIME/SYSTEMTIME or boost?
I have some code that deletes some files based on time_t comparisons with the last access date, and am looking for how to write a SetLastAccessTime method to use in my unit test.
Here's my Get:
bool GetLastAccessTime(const std::string &filename, time_t& lastAccessTime)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(filename.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return false;
FILETIME fTime = FindFileData.ftLastAccessTime;
FindClose(hFind);
SYSTEMTIME sTime;
FileTimeToSystemTime(&fTime, &sTime);
struct tm tmTime;
tmTime.tm_hour = sTime.wHour;
tmTime.tm_min = sTime.wMinute;
tmTime.tm_mday = sTime.wDay;
tmTime.tm_mon = sTime.wMonth;
tmTime.tm_sec = sTime.wSecond;
tmTime.tm_year = sTime.wYear - 1900;
time_t t = mktime(&tmTime);
lastAccessTime = t;
return true;
}
I'm guessing I do the reverse somehow? I'm not even really sure where I want to end up.
I'd much rather be doing somethi开发者_JAVA百科ng like this:
boost::filesystem::path p(filename)
std::time_t t = boost::filesystem::last_access_time(p);
but that doesn't seem to exist, from what I've been able to find (though there is a last_write_time). If there is another boost::filesystem technique of some sort that I've overlooked, I'm certainly open to that.
System: Win32(XP), Boost libraries: 1.44 v2, Dev env: Visual Studio TS 2008
From the Win32 API: SetFileTime. As stated in the documentation, you can pass in NULL if you don't want to change the other time stamps.
Whatever you're doing, be careful with it. In Vista or more recent forms of Windows, the Last Access Time is not actually modified on access, just on writes, and is therefore an alias for Last Modified. This gains a lot of file system efficiency- you're not writing timestamps when you open a file- but makes your operation, which I assume is to delete files nobody cares about, highly dangerous. The Debugging Tools for Windows team had to code around exactly this in agestore.exe, a tool that does exactly that for symbol files. (The tool fails to run, and prints a stern error message, if Windows isn't configured to set last access times.)
Can't you use SetFileTime, being the analog of GetFileTime?
精彩评论