From 7b5f1073419d0bca31aec9b1be6ce3e5f72b110f Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Sat, 7 Oct 2023 12:11:38 +0200 Subject: [PATCH] fs/FileInfo: add GetFileInformationByHandleEx() wrapper --- src/fs/FileInfo.cxx | 41 +++++++++++++++++++++++++++++++++++++++++ src/fs/FileInfo.hxx | 15 +++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/fs/FileInfo.cxx b/src/fs/FileInfo.cxx index f59e34deb..86b6904a5 100644 --- a/src/fs/FileInfo.cxx +++ b/src/fs/FileInfo.cxx @@ -5,6 +5,11 @@ #include "lib/fmt/PathFormatter.hxx" #include "lib/fmt/SystemError.hxx" +#ifdef _WIN32 +#include // for HWND (needed by winbase.h) +#include // for FILE_*_INFO +#endif + FileInfo::FileInfo(Path path, bool follow_symlinks) { if (!GetFileInfo(path, *this, follow_symlinks)) { @@ -15,3 +20,39 @@ FileInfo::FileInfo(Path path, bool follow_symlinks) #endif } } + +#ifdef _WIN32 + +FileInfo::FileInfo(HANDLE handle) +{ + if (!GetFileInfoByHandle(handle, *this)) + throw MakeLastError("Failed to access file"); +} + +bool +GetFileInfoByHandle(HANDLE handle, FileInfo &info) noexcept +{ + FILE_BASIC_INFO basic; + FILE_STANDARD_INFO standard; + + if (!GetFileInformationByHandleEx(handle, FileBasicInfo, + &basic, sizeof(basic)) || + !GetFileInformationByHandleEx(handle, FileStandardInfo, + &standard, sizeof(standard))) + return false; + + info.data.dwFileAttributes = basic.FileAttributes; + info.data.ftCreationTime.dwLowDateTime = basic.CreationTime.LowPart; + info.data.ftCreationTime.dwHighDateTime = basic.CreationTime.HighPart; + info.data.ftLastAccessTime.dwLowDateTime = basic.LastAccessTime.LowPart; + info.data.ftLastAccessTime.dwHighDateTime = basic.LastAccessTime.HighPart; + info.data.ftLastWriteTime.dwLowDateTime = basic.LastWriteTime.LowPart; + info.data.ftLastWriteTime.dwHighDateTime = basic.LastWriteTime.HighPart; + + info.data.nFileSizeLow = standard.EndOfFile.LowPart; + info.data.nFileSizeHigh = standard.EndOfFile.HighPart; + + return true; +} + +#endif // _WIN32 diff --git a/src/fs/FileInfo.hxx b/src/fs/FileInfo.hxx index d82a58208..25ff45a91 100644 --- a/src/fs/FileInfo.hxx +++ b/src/fs/FileInfo.hxx @@ -17,6 +17,10 @@ class FileInfo { friend bool GetFileInfo(Path path, FileInfo &info, bool follow_symlinks) noexcept; +#ifdef _WIN32 + friend bool GetFileInfoByHandle(HANDLE handle, FileInfo &info) noexcept; +#endif + friend class FileReader; #ifdef _WIN32 @@ -30,6 +34,10 @@ public: explicit FileInfo(Path path, bool follow_symlinks=true); +#ifdef _WIN32 + explicit FileInfo(HANDLE handle); +#endif + constexpr bool IsRegular() const noexcept { #ifdef _WIN32 return (data.dwFileAttributes & @@ -97,3 +105,10 @@ GetFileInfo(Path path, FileInfo &info, bool follow_symlinks=true) noexcept return ret == 0; #endif } + +#ifdef _WIN32 + +bool +GetFileInfoByHandle(HANDLE handle, FileInfo &info) noexcept; + +#endif