曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5768|回复: 0
打印 上一主题 下一主题

[文件与IO] GetFileTime() -- 获取文件时间戳

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2011-9-19 11:54:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
GetFileTime() 函数用来获取文件时间戳,它关乎 3 个时间属性概念:文件创建时间,文件访问时间,文件上一次修改时间。该函数原型如下:
[Plain Text] 纯文本查看 复制代码
BOOL WINAPI GetFileTime(
  __in       HANDLE hFile,
  __out_opt  LPFILETIME lpCreationTime,
  __out_opt  LPFILETIME lpLastAccessTime,
  __out_opt  LPFILETIME lpLastWriteTime
);

第 1 个参数为文件句柄;第 2 个参数为创建时间的 FILETIME 结构的指针;第 3 个参数为访问时间的 FILETIME 结构的指针;第 4 个参数为修改时间的 FILETIME 结构的指针。

当使用 GetFileTime() 获取文件时间后,为了更加直观的显示出时间,需要用 FileTimeToSystemTime() 函数进行时间的转换,转换出来的是 UTC 时间。

测试代码
[C++] 纯文本查看 复制代码
#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE        hFile;
    FILETIME    Creation, Access, LastWrite;
    SYSTEMTIME    SystemTime;

    hFile = CreateFile (_T("a.txt"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    GetFileTime(hFile, &Creation, &Access, &LastWrite);

    FileTimeToSystemTime (&Creation, &SystemTime);
    _ftprintf(stdout, _T("File creation time is: %d/%d/%d/ %d:%d\n"), SystemTime.wYear, SystemTime.wMonth, SystemTime.wDay, SystemTime.wHour+8, SystemTime.wMinute);

    FileTimeToSystemTime (&Access, &SystemTime);
    _ftprintf(stdout, _T("File Access time is: %d/%d/%d/ %d:%d\n"), SystemTime.wYear, SystemTime.wMonth, SystemTime.wDay, SystemTime.wHour+8, SystemTime.wMinute);

    FileTimeToSystemTime (&LastWrite, &SystemTime);
    _ftprintf(stdout, _T("File last write time is: %d/%d/%d/ %d:%d\n"), SystemTime.wYear, SystemTime.wMonth, SystemTime.wDay, SystemTime.wHour+8, SystemTime.wMinute);

    return 0;
}

运行输出:
D:\WindowsAPP\GetFileTime\Debug>GetFileTime.exe
File creation time is: 2011/9/19/ 11:23
File Access time is: 2011/9/19/ 11:23
File last write time is: 2011/9/19/ 11:27
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-6-18 19:14 , Processed in 0.080391 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表