Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1073)

Unified Diff: base/file_util.cc

Issue 157593005: Added new ReadFileToString API with a max_size argument (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Added new ReadFileToString API with a max_size argument Created 6 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: base/file_util.cc
diff --git a/base/file_util.cc b/base/file_util.cc
index e44f713cdb31828010ad9be92739a3d021dc4685..e0bc02d772960a891b8987b14e6c42f8bb726e25 100644
--- a/base/file_util.cc
+++ b/base/file_util.cc
@@ -126,7 +126,9 @@ bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2) {
return true;
}
-bool ReadFileToString(const FilePath& path, std::string* contents) {
+static bool ReadFileToStringImpl(const FilePath& path,
+ std::string* contents,
+ size_t maxsize) {
if (path.ReferencesParent())
return false;
FILE* file = OpenFile(path, "rb");
@@ -136,7 +138,18 @@ bool ReadFileToString(const FilePath& path, std::string* contents) {
char buf[1 << 16];
size_t len;
+ size_t size = 0;
+
+ // Many files supplied in path have incorrect size (proc files, streams etc)
+ // hence the file is read sequentially as opposed to one-shot read.
while ((len = fread(buf, 1, sizeof(buf), file)) > 0) {
+ if ((maxsize - size) < len) {
+ if (contents)
+ contents->clear();
+ CloseFile(file);
+ return false;
+ }
+ size += len;
if (contents)
contents->append(buf, len);
}
@@ -145,6 +158,16 @@ bool ReadFileToString(const FilePath& path, std::string* contents) {
return true;
}
+bool ReadFileToString(const FilePath& path,
+ std::string* contents,
+ size_t maxsize) {
+ return ReadFileToStringImpl(path, contents, maxsize);
+}
+
+bool ReadFileToString(const FilePath& path, std::string* contents) {
+ return ReadFileToStringImpl(path, contents, ~(size_t)0);
Andrew T Wilson (Slow) 2014/02/11 10:27:12 Can you use SIZE_MAX here instead of ~0? I'm OK w
kaliamoorthi 2014/02/11 16:29:16 Changed to std::numeric_limits<size_t>::max() as d
+}
+
bool IsDirectoryEmpty(const FilePath& dir_path) {
FileEnumerator files(dir_path, false,
FileEnumerator::FILES | FileEnumerator::DIRECTORIES);

Powered by Google App Engine
This is Rietveld 408576698