From 28a9781c513d2919a30a6db09aebb64a639f38e6 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Fri, 18 Jun 2021 01:34:52 -0700 Subject: [PATCH] util::read_file: fix reading from sysfs and add test case (#21325) * add sysfs test case * Revert "util.cc: refactor read_file (#21321)" This reverts commit 2a9ba3e867e4ba8ea8818a5be24807301a945f17. old-commit-hash: d90d9b2280397bb113c0d5835810cbd5f483f2a1 --- selfdrive/common/tests/test_util.cc | 4 ++++ selfdrive/common/util.cc | 25 +++++++++++++------------ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/selfdrive/common/tests/test_util.cc b/selfdrive/common/tests/test_util.cc index 42c57940e5..06261d01ad 100644 --- a/selfdrive/common/tests/test_util.cc +++ b/selfdrive/common/tests/test_util.cc @@ -24,6 +24,10 @@ TEST_CASE("util::read_file") { std::string ret = util::read_file("/proc/version"); REQUIRE(ret.find("Linux version") != std::string::npos); } + SECTION("read from sysfs") { + std::string ret = util::read_file("/sys/power/wakeup_count"); + REQUIRE(!ret.empty()); + } SECTION("read file") { char filename[] = "/tmp/test_read_XXXXXX"; int fd = mkstemp(filename); diff --git a/selfdrive/common/util.cc b/selfdrive/common/util.cc index ee3f364105..af87d9c22f 100644 --- a/selfdrive/common/util.cc +++ b/selfdrive/common/util.cc @@ -54,25 +54,26 @@ int set_core_affinity(int core) { namespace util { std::string read_file(const std::string& fn) { - std::ifstream f(fn, std::ios::binary | std::ios::in); - if (f) { - f.seekg(0, std::ios::end); - int pos = f.tellg(); + std::ifstream ifs(fn, std::ios::binary | std::ios::ate); + if (ifs) { + int pos = ifs.tellg(); if (pos > 0) { std::string result; result.resize(pos); - f.seekg(0, std::ios::beg); - if (f.read(result.data(), pos)) { + ifs.seekg(0, std::ios::beg); + ifs.read(result.data(), pos); + if (ifs) { return result; } - } else { - // fallback for files created on read, e.g. procfs - std::stringstream buffer; - buffer << f.rdbuf(); - return buffer.str(); } } - return std::string(); + ifs.close(); + + // fallback for files created on read, e.g. procfs + std::ifstream f(fn); + std::stringstream buffer; + buffer << f.rdbuf(); + return buffer.str(); } int read_files_in_dir(const std::string &path, std::map *contents) {