CreateFile GetFileTIme SetFileTime

时间:2011-02-15 00:18:02

标签: c++ winapi

我在使用GetFileTime和SetFileTime时遇到了麻烦 说到目录。具体来说,我认为我的问题是 我是WinAPI的新手,我不认为我得到了 处理正确。

有两种情况。

首先,我只需要一个句柄来获取文件或目录 时间戳(创建,访问,mod)。我想以安全和灵活的方式处理这个问题。 不要在参数上过于慷慨。

在第二个,我需要一个句柄,允许我修改文件或direcotry 时间戳。我还想以最小的权利创建这个句柄,但是以灵活可靠的方式。

灵活的我的意思是,在这两种情况下,我都需要代码在localy,网络共享和多线程应用程序中工作。多线程部分不是必需的,因为我的应用程序不会在文件/目录上创建多个句柄,但有可能在后台运行其他应用程序。

//QUESTION 1:
//I do this when I just need a handle to **GET** some attributes like dates.
//(here I just need a handle to get info I am not modding the item).
//Am I using the correct params if I need it to work in a 
//local + networked environment and also in a multi-threaded app???
h1 = CreateFile(itemA, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (h1 == INVALID_HANDLE_VALUE){

    return 0;
}
//QUESTION 2:
//The above works for local files but not local dirs.
//How can I get the above to work for dirs? (Same environment considerations).


//QUESTION 3:
//I do this when I just need a handle to ***SET*** some attributes (like timestamps).
//(here I need a handle that allows me to modd the items timestamp).
//Am I using the correct params if I need it to work in a 
//local + networked environment and also in a multi-threaded app???
hItemB = CreateFile(itemB, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (hItemB == INVALID_HANDLE_VALUE){
    return 0;
}
//QUESTION 4:
//The above works for local files but not local dirs.
//How can I get the above to work for dirs? (Same environment considerations).

2 个答案:

答案 0 :(得分:4)

回答#2:要使用CreateFile获取目录句柄,需要使用FILE_FLAG_BACKUP_SEMANTICS标志。使用你的例子:

h1 = CreateFile(itemA, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);

我猜这也适用于答案#4,但我还没有尝试过确认。

答案 1 :(得分:0)

以下是有关如何根据DOS日期时间戳设置目录日期的代码示例。

int Directory_SetDosTime(char *Path, unsigned int DosDateTime)
{
    FILETIME LocalTime, FileTime;
    HANDLE Handle;
    SYSTEMTIME SystemTime;


    DosDateTimeToFileTime((DosDateTime >> 16), DosDateTime, &LocalTime);
    LocalFileTimeToFileTime(&LocalTime, &FileTime);
    FileTimeToSystemTime(&FileTime, &SystemTime);

    Handle = CreateFile(Path, GENERIC_WRITE, FILE_SHARE_WRITE,
                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

    if (Handle == INVALID_HANDLE_VALUE)
    {
        //Unable to open directory
        return FALSE;
    }

    if (SetFileTime(Handle, &FileTime, &FileTime, &FileTime) == 0)
    {
        //Unable to set directory time
        CloseHandle(Handle);
        return FALSE;
    }

    CloseHandle(Handle);
    return TRUE;
}