Skip to content

Commit

Permalink
FileSystem: Use _filelengthi64 to get the file size on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
CookiePLMonster authored and stenzek committed Jul 19, 2023
1 parent d96dea4 commit c82f800
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions common/FileSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

#if defined(_WIN32)
#include "RedtapeWindows.h"
#include <io.h>
#include <winioctl.h>
#include <share.h>
#include <shlobj.h>
Expand Down Expand Up @@ -747,6 +748,13 @@ s64 FileSystem::FTell64(std::FILE* fp)

s64 FileSystem::FSize64(std::FILE* fp)
{
#ifdef _WIN32
const int fd = _fileno(fp);
if (fd >= 0)
{
return _filelengthi64(fd);
}
#else
const s64 pos = FTell64(fp);
if (pos >= 0)
{
Expand All @@ -757,6 +765,7 @@ s64 FileSystem::FSize64(std::FILE* fp)
return size;
}
}
#endif

return -1;
}
Expand All @@ -781,12 +790,11 @@ std::optional<std::vector<u8>> FileSystem::ReadBinaryFile(const char* filename)

std::optional<std::vector<u8>> FileSystem::ReadBinaryFile(std::FILE* fp)
{
std::fseek(fp, 0, SEEK_END);
const long size = std::ftell(fp);
std::fseek(fp, 0, SEEK_SET);
const s64 size = FSize64(fp);
if (size < 0)
return std::nullopt;

std::fseek(fp, 0, SEEK_SET);
std::vector<u8> res(static_cast<size_t>(size));
if (size > 0 && std::fread(res.data(), 1u, static_cast<size_t>(size), fp) != static_cast<size_t>(size))
return std::nullopt;
Expand All @@ -805,12 +813,11 @@ std::optional<std::string> FileSystem::ReadFileToString(const char* filename)

std::optional<std::string> FileSystem::ReadFileToString(std::FILE* fp)
{
std::fseek(fp, 0, SEEK_END);
const long size = std::ftell(fp);
std::fseek(fp, 0, SEEK_SET);
const s64 size = FSize64(fp);
if (size < 0)
return std::nullopt;

std::fseek(fp, 0, SEEK_SET);
std::string res;
res.resize(static_cast<size_t>(size));
// NOTE - assumes mode 'rb', for example, this will fail over missing Windows carriage return bytes
Expand Down

0 comments on commit c82f800

Please sign in to comment.