From ec851c9d6d328dcc1ae3be215edc50329069275b Mon Sep 17 00:00:00 2001 From: Stenzek Date: Mon, 8 Jul 2024 20:54:31 +1000 Subject: [PATCH] FileSystem: Add FTruncate64() --- src/common/file_system.cpp | 40 ++++++++++++++++++++++++++++++++++++++ src/common/file_system.h | 1 + 2 files changed, 41 insertions(+) diff --git a/src/common/file_system.cpp b/src/common/file_system.cpp index c94caef15..ecd7e138a 100644 --- a/src/common/file_system.cpp +++ b/src/common/file_system.cpp @@ -26,6 +26,7 @@ #if defined(_WIN32) #include "windows_headers.h" +#include #include #include #include @@ -1122,6 +1123,45 @@ s64 FileSystem::FSize64(std::FILE* fp) return -1; } +bool FileSystem::FTruncate64(std::FILE* fp, s64 size, Error* error) +{ + const int fd = fileno(fp); + if (fd < 0) + { + Error::SetErrno(error, "fileno() failed: ", errno); + return false; + } + +#ifdef _WIN32 + const errno_t err = _chsize_s(fd, size); + if (err != 0) + { + Error::SetErrno(error, "_chsize_s() failed: ", err); + return false; + } + + return true; +#else + // Prevent truncation on platforms which don't have a 64-bit off_t. + if constexpr (sizeof(off_t) != sizeof(s64)) + { + if (size < std::numeric_limits::min() || size > std::numeric_limits::max()) + { + Error::SetStringView(error, "File size is too large."); + return false; + } + } + + if (ftruncate(fd, static_cast(size)) < 0) + { + Error::SetErrno(error, "ftruncate() failed: ", errno); + return false; + } + + return true; +#endif +} + s64 FileSystem::GetPathFileSize(const char* Path) { FILESYSTEM_STAT_DATA sd; diff --git a/src/common/file_system.h b/src/common/file_system.h index 9175d217a..971c285db 100644 --- a/src/common/file_system.h +++ b/src/common/file_system.h @@ -109,6 +109,7 @@ std::FILE* OpenCFile(const char* filename, const char* mode, Error* error = null int FSeek64(std::FILE* fp, s64 offset, int whence); s64 FTell64(std::FILE* fp); s64 FSize64(std::FILE* fp); +bool FTruncate64(std::FILE* fp, s64 size, Error* error = nullptr); int OpenFDFile(const char* filename, int flags, int mode, Error* error = nullptr);