util.cc: refactor read_file (#21350)
old-commit-hash: ac71384a28cda46126ea5d699697bb7ab701d972
This commit is contained in:
@@ -54,26 +54,26 @@ 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();
|
||||
if (pos > 0) {
|
||||
std::string result;
|
||||
result.resize(pos);
|
||||
ifs.seekg(0, std::ios::beg);
|
||||
ifs.read(result.data(), pos);
|
||||
if (ifs) {
|
||||
std::ifstream f(fn, std::ios::binary | std::ios::in);
|
||||
if (f.is_open()) {
|
||||
f.seekg(0, std::ios::end);
|
||||
int size = f.tellg();
|
||||
if (f.good() && size > 0) {
|
||||
std::string result(size, '\0');
|
||||
f.seekg(0, std::ios::beg);
|
||||
f.read(result.data(), size);
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
// 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) {
|
||||
|
||||
Reference in New Issue
Block a user