当涉及到目录时,我在使用GetFileTime和SetFileTime时遇到了问题。具体地说,我认为我的问题是我是WinAPI的新手,我认为我没有正确地掌握句柄。
有两种场景。
在第一个示例中,我只需要一个句柄来获取文件或目录的时间戳(create、access、mod)。我想以一种安全和灵活的方式来处理这个问题。我不想在参数上过于慷慨。
在第二个示例中,我需要一个句柄,它允许我修改文件或目录时间戳。我也想用最小的权限创建这个句柄,但要以灵活和可靠的方式。
我所说的灵活性是指,在这两种情况下,我都需要代码在本地、网络共享和多线程应用程序中工作。多线程部分是不必要的,因为我的应用程序不会在文件/目录上创建多个句柄,但在后台运行的其他应用程序可能会。
//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).发布于 2011-02-15 09:44:32
答案#2:要使用CreateFile获取目录的句柄,需要使用FILE_FLAG_BACKUP_SEMANTICS标志。使用您的示例:
h1 = CreateFile(itemA, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);我猜这也适用于答案#4,但我还没有尝试确认。
发布于 2011-05-07 16:04:12
下面是一个关于如何根据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;
}https://stackoverflow.com/questions/4998814
复制相似问题