windows VC++:如何获取文件的时间和日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1051667/
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
VC++: How to get the time and date of a file?
提问by Qwertie
How do I get the file size and date stamp of a file on Windows in C++, given its path?
给定路径,如何在 C++ 中的 Windows 上获取文件的文件大小和日期戳?
采纳答案by DannyT
You can use FindFirstFile()
to get them both at once, without having to open it (which is required by GetFileSize()
and GetInformationByHandle()
). It's a bit laborious, however, so a little wrapper is helpful
您可以使用FindFirstFile()
一次获取它们,而无需打开它(这是GetFileSize()
和要求的GetInformationByHandle()
)。然而,这有点费力,所以一个小包装是有帮助的
bool get_file_information(LPCTSTR path, WIN32_FIND_DATA* data)
{
HANDLE h = FindFirstFile(path, &data);
if(INVALID_HANDLE_VALUE != h) {
return false;
} else {
FindClose(h);
return true;
}
}
Then the file size is available in the nFileSizeHigh
and nFileSizeLow
members of WIN32_FIND_DATA, and the timestamps are available in the ftCreationTime
, ftLastAccessTime
and ftLastWriteTime
members.
然后文件大小在WIN32_FIND_DATA的nFileSizeHigh
andnFileSizeLow
成员中可用,时间戳在ftCreationTime
, ftLastAccessTime
andftLastWriteTime
成员中可用。
回答by Michael
GetFileSize/GetFileSizeExand GetFileInformationByHandleExwith FileBasicInfo can be used to retrieved this information.
GetFileSize/ GetFileSizeEx和GetFileInformationByHandleEx与 FileBasicInfo 可用于检索此信息。
Both functions take a handle, so you need to use CreateFile on the path prior to calling these functions.
这两个函数都有一个句柄,因此您需要在调用这些函数之前在路径上使用 CreateFile。
// Error handling removed for brevity
HANDLE hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
LARGE_INTEGER fileSize;
GetFileSizeEx(hFile, &fileSize);
FILE_BASIC_INFO fileInfo);
GetFileInformationByHandle(hFile, FileBasicInfo, fileInfo, sizeof(fileInfo));
// fileInfo.CreationTime is when file was created.
回答by Matthew Iselin
You could also use POSIX stat, if you were looking for portability. Windows still supports its use.
如果您正在寻找可移植性,您也可以使用POSIX stat。Windows 仍然支持它的使用。
回答by Shane Powell
To append the other answer, you call GetFileTimeto get just the file times. This API also requries a handle and I think is easier than GetFileInformationByHandle API. BTW the GetFileInformationByHandleEx is only supported in VISTA and above.
要附加另一个答案,您可以调用GetFileTime来获取文件时间。这个 API 还需要一个句柄,我认为它比 GetFileInformationByHandle API 更容易。顺便说一句,GetFileInformationByHandleEx 仅在 VISTA 及更高版本中受支持。