FileSystem: Add FTruncate64()

This commit is contained in:
Stenzek 2024-07-08 20:54:31 +10:00
parent 36abbd97e8
commit ec851c9d6d
No known key found for this signature in database
2 changed files with 41 additions and 0 deletions

View file

@ -26,6 +26,7 @@
#if defined(_WIN32) #if defined(_WIN32)
#include "windows_headers.h" #include "windows_headers.h"
#include <io.h>
#include <malloc.h> #include <malloc.h>
#include <pathcch.h> #include <pathcch.h>
#include <share.h> #include <share.h>
@ -1122,6 +1123,45 @@ s64 FileSystem::FSize64(std::FILE* fp)
return -1; 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<off_t>::min() || size > std::numeric_limits<off_t>::max())
{
Error::SetStringView(error, "File size is too large.");
return false;
}
}
if (ftruncate(fd, static_cast<off_t>(size)) < 0)
{
Error::SetErrno(error, "ftruncate() failed: ", errno);
return false;
}
return true;
#endif
}
s64 FileSystem::GetPathFileSize(const char* Path) s64 FileSystem::GetPathFileSize(const char* Path)
{ {
FILESYSTEM_STAT_DATA sd; FILESYSTEM_STAT_DATA sd;

View file

@ -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); int FSeek64(std::FILE* fp, s64 offset, int whence);
s64 FTell64(std::FILE* fp); s64 FTell64(std::FILE* fp);
s64 FSize64(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); int OpenFDFile(const char* filename, int flags, int mode, Error* error = nullptr);