From f0fc611f1582bb64f850400e9766e31e523e9fba Mon Sep 17 00:00:00 2001 From: Pierre Bourdon Date: Mon, 16 Sep 2013 06:56:49 +0200 Subject: [PATCH] Add a hacky check for text file size in ReadFileToString. Fixes issue 6455. --- Source/Core/Common/Src/FileUtil.cpp | 28 +++++++++++++++++++++++++++- Source/Core/Common/Src/FileUtil.h | 8 ++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Source/Core/Common/Src/FileUtil.cpp b/Source/Core/Common/Src/FileUtil.cpp index 982f7e79de..7663e11078 100644 --- a/Source/Core/Common/Src/FileUtil.cpp +++ b/Source/Core/Common/Src/FileUtil.cpp @@ -885,8 +885,34 @@ bool ReadFileToString(bool text_file, const char *filename, std::string &str) if (!f) return false; + size_t read_size; str.resize(GetSize(f)); - return file.ReadArray(&str[0], str.size()); + bool retval = file.ReadArray(&str[0], str.size(), &read_size); + + // On Windows, reading a text file automatically translates \r\n to \n. + // This means we will read less characters than the expected size of the + // file. In that case, ignore the return value and count ourselves. +#ifdef _WIN32 + if (text_file) + { + size_t count = 0; + for (size_t i = 0; i < read_size; ++i) + { + if (str[i] == '\n') + count += 2; + else + count += 1; + } + + if (count != str.size()) + return false; + + str.resize(read_size); + return true; + } +#endif + + return retval; } IOFile::IOFile() diff --git a/Source/Core/Common/Src/FileUtil.h b/Source/Core/Common/Src/FileUtil.h index 6d0a440f69..e3263ba233 100644 --- a/Source/Core/Common/Src/FileUtil.h +++ b/Source/Core/Common/Src/FileUtil.h @@ -161,11 +161,15 @@ public: bool Close(); template - bool ReadArray(T* data, size_t length) + bool ReadArray(T* data, size_t length, size_t* pReadBytes = NULL) { - if (!IsOpen() || length != std::fread(data, sizeof(T), length, m_file)) + size_t read_bytes = 0; + if (!IsOpen() || length != (read_bytes = std::fread(data, sizeof(T), length, m_file))) m_good = false; + if (pReadBytes) + *pReadBytes = read_bytes; + return m_good; }