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

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..243d8e7885b63d01224e0a86f033f6f2398d97e3 100644
--- a/base/file_util.cc
+++ b/base/file_util.cc
@@ -10,6 +10,7 @@
#include <stdio.h>
#include <fstream>
+#include <limits>
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
@@ -126,7 +127,11 @@ bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2) {
return true;
}
-bool ReadFileToString(const FilePath& path, std::string* contents) {
+bool ReadFileToString(const FilePath& path,
+ std::string* contents,
+ size_t max_size) {
+ if(contents)
Andrew T Wilson (Slow) 2014/02/17 14:38:22 Two things: 1) space before the open paren. 2) th
kaliamoorthi 2014/02/18 11:50:50 I have fixed 1 in a new patch.
+ contents->clear();
if (path.ReferencesParent())
return false;
FILE* file = OpenFile(path, "rb");
@@ -136,13 +141,29 @@ bool ReadFileToString(const FilePath& path, std::string* contents) {
char buf[1 << 16];
size_t len;
+ size_t size = 0;
+ bool return_var = true;
Andrew T Wilson (Slow) 2014/02/17 14:38:22 Change this name to something like "read_status".
kaliamoorthi 2014/02/18 11:50:50 Done.
+
+ // Many files supplied in |path| have incorrect size (proc files etc).
+ // Hence, the file is read sequentially as opposed to a one-shot read.
while ((len = fread(buf, 1, sizeof(buf), file)) > 0) {
- if (contents)
- contents->append(buf, len);
+ if (contents && (max_size - size) > 0)
+ contents->append(buf, std::min(len, max_size - size));
+
+ if ((max_size - size) < len) {
+ return_var = false;
+ break;
+ }
+
+ size += len;
}
CloseFile(file);
- return true;
+ return return_var;
+}
+
+bool ReadFileToString(const FilePath& path, std::string* contents) {
+ return ReadFileToString(path, contents, std::numeric_limits<size_t>::max());
}
bool IsDirectoryEmpty(const FilePath& dir_path) {
« base/file_util.h ('K') | « base/file_util.h ('k') | base/file_util_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698