diff options
author | Vasil Dimov <vd@FreeBSD.org> | 2020-11-18 17:34:41 +0100 |
---|---|---|
committer | Vasil Dimov <vd@FreeBSD.org> | 2021-03-01 12:57:00 +0100 |
commit | 8b6e4b3b23027da263d257b342f5d9a53e4032d5 (patch) | |
tree | adf38dbe37cfdb8a32b6766247b3884c05927e5a | |
parent | 4cba2fdafa483cbdb70f581174138ec253c80d48 (diff) |
util: fix ReadBinaryFile() returning partial contents
If an error occurs and `fread()` returns `0` (nothing was read) then the
code before this patch would have returned "success" with a partially
read contents of the file.
-rw-r--r-- | src/util/readwritefile.cpp | 8 |
1 files changed, 3 insertions, 5 deletions
diff --git a/src/util/readwritefile.cpp b/src/util/readwritefile.cpp index 1d9beb111f..15e9d7a9b9 100644 --- a/src/util/readwritefile.cpp +++ b/src/util/readwritefile.cpp @@ -17,8 +17,8 @@ std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxs return std::make_pair(false,""); std::string retval; char buffer[128]; - size_t n; - while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) { + do { + const size_t n = fread(buffer, 1, sizeof(buffer), f); // Check for reading errors so we don't return any data if we couldn't // read the entire file (or up to maxsize) if (ferror(f)) { @@ -26,9 +26,7 @@ std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxs return std::make_pair(false,""); } retval.append(buffer, buffer+n); - if (retval.size() > maxsize) - break; - } + } while (!feof(f) && retval.size() <= maxsize); fclose(f); return std::make_pair(true,retval); } |