Improve the file size check when reading text files

This commit is contained in:
Henrik Rydgård committed 2024-01-25 12:34:19 +01:00
1 parent aa9b0785a5
commit 9218efd286
2 files changed
+11 -6

No files matched your search

+8 -3
View File
@@ -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.
@@ -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;
+3 -3
View File
@@ -202,10 +202,10 @@ private:
// 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) {