fix: util::file_exists will return false on no permissions (#21880)

* fix bug

* add test case
old-commit-hash: 3a7959b5ff
commatwo_master
Dean Lee 4 years ago committed by GitHub
parent 3c828f9fbf
commit 16c727b65c
  1. 24
      selfdrive/common/tests/test_util.cc
  2. 6
      selfdrive/common/util.cc

@ -1,5 +1,6 @@
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
@ -51,3 +52,26 @@ TEST_CASE("util::read_file") {
REQUIRE(util::read_file("/proc/kmsg").empty());
}
}
TEST_CASE("util::file_exists") {
char filename[] = "/tmp/test_file_exists_XXXXXX";
int fd = mkstemp(filename);
REQUIRE(fd != -1);
close(fd);
SECTION("existent file") {
REQUIRE(util::file_exists(filename));
REQUIRE(util::file_exists("/tmp"));
}
SECTION("nonexistent file") {
std::string fn = filename;
REQUIRE(!util::file_exists(fn + "/nonexistent"));
}
SECTION("file has no access permissions") {
std::string fn = "/proc/kmsg";
std::ifstream f(fn);
REQUIRE(f.good() == false);
REQUIRE(util::file_exists(fn));
}
::remove(filename);
}

@ -1,5 +1,7 @@
#include "selfdrive/common/util.h"
#include <sys/stat.h>
#include <cassert>
#include <cerrno>
#include <cstring>
@ -113,8 +115,8 @@ std::string readlink(const std::string &path) {
}
bool file_exists(const std::string& fn) {
std::ifstream f(fn);
return f.good();
struct stat st = {};
return stat(fn.c_str(), &st) != -1;
}
std::string getenv(const char* key, const char* default_val) {

Loading…
Cancel
Save