util.cc: refactor read_file (#21295)

* mode read & open once

* change return statement for better readibility

* apply reviews

* Update selfdrive/common/util.cc

* fix

Co-authored-by: Adeeb Shihadeh <adeebshihadeh@gmail.com>
pull/21322/head
Dean Lee 4 years ago committed by GitHub
parent fc569694e9
commit 190a845505
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 24
      selfdrive/common/util.cc

@ -54,26 +54,24 @@ 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 | std::ios::ate);
if (f) {
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<std::string, std::string> *contents) {

Loading…
Cancel
Save