C++ 获取文件上次修改时间并比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1938939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get File Last Modify Time and Compare
提问by Fraklin
I want a piece of function which will take a file and last how many days, if it was older than that date, will return 0 otherwise 1... Something like that...
我想要一个函数,它会接受一个文件并持续多少天,如果它早于那个日期,将返回 0 否则返回 1 ......类似的东西......
For example:
例如:
int IsOlder(TCHAR *filename, int days)
{
do operation.
If last modify date was older than days variable
return 0
else
return 1
}
It's MS VC++ 6 for Windows. Thanks from now!
它是适用于 Windows 的 MS VC++ 6。从现在开始感谢!
回答by Julien-L
Windows has an API function called GetFileTime()
(doc on MSDN) taking a file handle in parameter and 3 FILETIME
structures to be filled with date-time info:
Windows 有一个名为GetFileTime()
(MSDN 上的 doc)的 API 函数,它在参数和 3 个FILETIME
结构中使用一个文件句柄来填充日期时间信息:
FILETIME creationTime,
lpLastAccessTime,
lastWriteTime;
bool err = GetFileTime( h, &creationTime, &lpLastAccessTime, &lastWriteTime );
if( !err ) error
The FILETIME
structure is obfuscated, use the function FileTimeToSystemTime()
to translate it to a SYSTEMTIME
structure which is way easier to use:
该FILETIME
结构进行模糊处理,使用该功能FileTimeToSystemTime()
将其转换为一个SYSTEMTIME
就是用比较容易的方式结构:
SYSTEMTIME systemTime;
bool res = FileTimeToSystemTime( &creationTime, &systemTime );
if( !res ) error
Then you can use fields wYear
, wMonth
, etc. to compare with your number of days.
然后您可以使用 fields wYear
、wMonth
等与您的天数进行比较。
回答by Skurmedel
GetFileTimegets the various dates relevant to a file. There's an example.
GetFileTime获取与文件相关的各种日期。有一个例子。
You will need to fetch the last write time, and calculate the difference in days from there. As the GetFileTime
function returns the quite unwieldy FILETIME
structure you probably want to convert it into system time (struct SYSTEMTIME
) with FileTimeToSystemTime
.
您需要获取上次写入时间,并计算从那里开始的天数差异。由于该GetFileTime
函数返回相当笨拙的FILETIME
结构,您可能希望将其转换为系统时间 ( struct SYSTEMTIME
) FileTimeToSystemTime
。