Skip to content

Commit

Permalink
Improve the file size check when reading text files
Browse files Browse the repository at this point in the history
  • Loading branch information
hrydgard committed Jan 25, 2024
1 parent aa9b078 commit 9218efd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
11 changes: 8 additions & 3 deletions Common/File/FileUtil.cpp
Expand Up @@ -1147,8 +1147,8 @@ bool IOFile::Resize(uint64_t size)
return m_good;
}

bool ReadFileToStringOptions(bool text_file, bool allowShort, const Path &filename, std::string *str) {
FILE *f = File::OpenCFile(filename, text_file ? "r" : "rb");
bool ReadFileToStringOptions(bool textFile, bool allowShort, const Path &filename, std::string *str) {
FILE *f = File::OpenCFile(filename, textFile ? "r" : "rb");
if (!f)
return false;
// Warning: some files, like in /sys/, may return a fixed size like 4096.
Expand All @@ -1171,7 +1171,12 @@ bool ReadFileToStringOptions(bool text_file, bool allowShort, const Path &filena
str->resize(totalRead);
// Allow less, because some system files will report incorrect lengths.
// Also, when reading text with CRLF, the read length may be shorter.
success = (allowShort || text_file) ? (totalRead <= len) : (totalRead == len);
if (textFile) {
// totalRead doesn't take \r into account since they might be skipped in this mode.
// So let's just ask how far the cursor got.
totalRead = ftell(f);
}
success = allowShort ? (totalRead <= len) : (totalRead == len);
}
fclose(f);
return success;
Expand Down
6 changes: 3 additions & 3 deletions Common/File/FileUtil.h
Expand Up @@ -202,10 +202,10 @@ class IOFile {
// TODO: Refactor, this was moved from the old file_util.cpp.

// Whole-file reading/writing
bool WriteStringToFile(bool text_file, const std::string &str, const Path &filename);
bool WriteDataToFile(bool text_file, const void* data, size_t size, const Path &filename);
bool WriteStringToFile(bool textFile, const std::string &str, const Path &filename);
bool WriteDataToFile(bool textFile, const void* data, size_t size, const Path &filename);

bool ReadFileToStringOptions(bool text_file, bool allowShort, const Path &path, std::string *str);
bool ReadFileToStringOptions(bool textFile, bool allowShort, const Path &path, std::string *str);

// Wrappers that clarify the intentions.
inline bool ReadBinaryFileToString(const Path &path, std::string *str) {
Expand Down

0 comments on commit 9218efd

Please sign in to comment.