曲径通幽论坛

标题: SystemTimeToFileTime() -- 转换系统时间到文件时间 [打印本页]

作者: beyes    时间: 2011-9-9 21:32
标题: SystemTimeToFileTime() -- 转换系统时间到文件时间
SystemTimeToFileTime() 函数用来转换系统时间到文件时间,它经常和 SetFileTime() 一起使用,其功能就像 linux 下面的 touch 命令。

touch 命令的效果也是修改文件时间为当前系统时间,如:
[root@beyes   phpBB3]# ls -al code.html
-rw-r--r-- 1 root root 6546 Sep  9 16:31 code.html
[root@beyes   phpBB3]# touch code.html
[root@beyes   phpBB3]# ls -al code.html
-rw-r--r-- 1 root root 6546 Sep  9 19:25 code.html
上面的 code.html 的建立时间是 16:31,经过 touch 修改后就变为当前的系统时间。

下面利用这两个函数实现具有 touch 命令一样的修改时间功能。

首先在程序同一目录下建立一个文件,其修改时间为 2011‎年‎9‎月‎9‎日,‏‎19:33:35 。当我们过一会儿运行该程序时,会在资源管理器里发现该文件的修改时间已经改变。

程序代码:
[C++] 纯文本查看 复制代码

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
    SYSTEMTIME    sysTime;
    FILETIME    fileTime;
    HANDLE        hFile;

    hFile = CreateFile(_T("123.txt"), GENERIC_READ|GENERIC_WRITE, 0, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    
    GetSystemTime (&sysTime);
    SystemTimeToFileTime (&sysTime, &fileTime);

    SetFileTime(hFile, (LPFILETIME)NULL, (LPFILETIME)NULL, &fileTime);

    return 0;
}





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2