Skip to content

Commit

Permalink
FileSystem: Add FTruncate64()
Browse files Browse the repository at this point in the history
  • Loading branch information
stenzek committed Jul 9, 2024
1 parent 36abbd9 commit ec851c9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/common/file_system.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

#if defined(_WIN32)
#include "windows_headers.h"
#include <io.h>
#include <malloc.h>
#include <pathcch.h>
#include <share.h>
Expand Down Expand Up @@ -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<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)
{
FILESYSTEM_STAT_DATA sd;
Expand Down
1 change: 1 addition & 0 deletions src/common/file_system.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit ec851c9

Please sign in to comment.