From 0ef41b3e943950e3835b20f51cb619d42a35e6f7 Mon Sep 17 00:00:00 2001 From: Dean Lee Date: Fri, 18 Jun 2021 14:19:41 +0800 Subject: [PATCH] util.cc: refactor read_file (#21321) * mode read & open once * change return statement for better readibility * apply reviews * can't open with ate flag old-commit-hash: 8d5c61eefe91f9f62ae8109e2c0c32ed2778e770 --- selfdrive/common/util.cc | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/selfdrive/common/util.cc b/selfdrive/common/util.cc index af87d9c22..ee3f36410 100644 --- a/selfdrive/common/util.cc +++ b/selfdrive/common/util.cc @@ -54,26 +54,25 @@ int set_core_affinity(int core) { namespace util { std::string read_file(const std::string& fn) { - std::ifstream ifs(fn, std::ios::binary | std::ios::ate); - if (ifs) { - int pos = ifs.tellg(); + std::ifstream f(fn, std::ios::binary | std::ios::in); + if (f) { + f.seekg(0, std::ios::end); + int pos = f.tellg(); if (pos > 0) { std::string result; result.resize(pos); - ifs.seekg(0, std::ios::beg); - ifs.read(result.data(), pos); - if (ifs) { + f.seekg(0, std::ios::beg); + if (f.read(result.data(), pos)) { return result; } + } else { + // fallback for files created on read, e.g. procfs + std::stringstream buffer; + buffer << f.rdbuf(); + return buffer.str(); } } - ifs.close(); - - // fallback for files created on read, e.g. procfs - std::ifstream f(fn); - std::stringstream buffer; - buffer << f.rdbuf(); - return buffer.str(); + return std::string(); } int read_files_in_dir(const std::string &path, std::map *contents) {