util.cc: refactor read_file (#21350)

old-commit-hash: ac71384a28
commatwo_master
Dean Lee 4 years ago committed by GitHub
parent f883cfec39
commit f03ca47c9c
  1. 32
      selfdrive/common/util.cc

@ -54,26 +54,26 @@ int set_core_affinity(int core) {
namespace util { namespace util {
std::string read_file(const std::string& fn) { std::string read_file(const std::string& fn) {
std::ifstream ifs(fn, std::ios::binary | std::ios::ate); std::ifstream f(fn, std::ios::binary | std::ios::in);
if (ifs) { if (f.is_open()) {
int pos = ifs.tellg(); f.seekg(0, std::ios::end);
if (pos > 0) { int size = f.tellg();
std::string result; if (f.good() && size > 0) {
result.resize(pos); std::string result(size, '\0');
ifs.seekg(0, std::ios::beg); f.seekg(0, std::ios::beg);
ifs.read(result.data(), pos); f.read(result.data(), size);
if (ifs) { // return either good() or has reached end-of-file (e.g. /sys/power/wakeup_count)
if (f.good() || f.eof()) {
result.resize(f.gcount());
return result; return result;
} }
} }
// fallback for files created on read, e.g. procfs
std::stringstream buffer;
buffer << f.rdbuf();
return buffer.str();
} }
ifs.close(); return std::string();
// 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<std::string, std::string> *contents) { int read_files_in_dir(const std::string &path, std::map<std::string, std::string> *contents) {

Loading…
Cancel
Save