Add LoggingReadEntireFile for reading a file into a string

Change-Id: Ie07ef12131ef1d995aa78749091f3adacde75160
Reviewed-on: https://chromium-review.googlesource.com/492446
Commit-Queue: Joshua Peraza <jperaza@chromium.org>
Reviewed-by: Mark Mentovai <mark@chromium.org>
This commit is contained in:
Joshua Peraza 2017-05-01 20:40:01 -07:00 committed by Commit Bot
parent f03c7b2d8f
commit 8af3203d81
3 changed files with 30 additions and 15 deletions

View File

@ -156,6 +156,26 @@ void CheckedReadFileAtEOF(FileHandle file) {
}
}
bool LoggingReadEntireFile(const base::FilePath& path, std::string* contents) {
FileHandle handle = LoggingOpenFileForRead(path);
if (handle == kInvalidFileHandle) {
return false;
}
char buffer[4096];
FileOperationResult rv;
std::string local_contents;
while ((rv = ReadFile(handle, buffer, sizeof(buffer))) > 0) {
local_contents.append(buffer, rv);
}
if (rv < 0) {
PLOG(ERROR) << internal::kNativeReadFunctionName;
return false;
}
contents->swap(local_contents);
return true;
}
void CheckedCloseFile(FileHandle file) {
CHECK(LoggingCloseFile(file));
}

View File

@ -17,6 +17,8 @@
#include <sys/types.h>
#include <string>
#include "build/build_config.h"
#if defined(OS_POSIX)
@ -306,6 +308,12 @@ void CheckedWriteFile(FileHandle file, const void* buffer, size_t size);
//! \sa ReadFile
void CheckedReadFileAtEOF(FileHandle file);
//! brief Wraps LoggingOpenFileForRead() and ReadFile() reading the entire file
//! into \a contents.
//!
//! \return `true` on success, or `false` with a message logged.
bool LoggingReadEntireFile(const base::FilePath& path, std::string* contents);
//! \brief Wraps `open()` or `CreateFile()`, opening an existing file for
//! reading.
//!

View File

@ -31,6 +31,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "util/file/delimited_file_reader.h"
#include "util/file/file_io.h"
#include "util/file/file_reader.h"
#include "util/linux/scoped_ptrace_attach.h"
@ -78,20 +79,6 @@ bool AdvancePastNumber(const char** input, T* value) {
return false;
}
bool ReadEntireFile(const char* path, std::string* contents) {
FileReader file;
if (!file.Open(base::FilePath(path))) {
return false;
}
char buffer[4096];
FileOperationResult length;
while ((length = file.Read(buffer, sizeof(buffer))) > 0) {
contents->append(buffer, length);
}
return length >= 0;
}
void SubtractTimespec(const timespec& t1, const timespec& t2,
timespec* result) {
result->tv_sec = t1.tv_sec - t2.tv_sec;
@ -391,7 +378,7 @@ bool ProcessInfo::StartTime(timeval* start_time) const {
char path[32];
snprintf(path, sizeof(path), "/proc/%d/stat", pid_);
std::string stat_contents;
if (!ReadEntireFile(path, &stat_contents)) {
if (!LoggingReadEntireFile(base::FilePath(path), &stat_contents)) {
return false;
}