diff --git a/selfdrive/common/tests/test_util.cc b/selfdrive/common/tests/test_util.cc index 06261d01ad..d61ca38886 100644 --- a/selfdrive/common/tests/test_util.cc +++ b/selfdrive/common/tests/test_util.cc @@ -1,5 +1,6 @@ #include +#include #include #include @@ -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); +} diff --git a/selfdrive/common/util.cc b/selfdrive/common/util.cc index 2771d76668..cf570430e4 100644 --- a/selfdrive/common/util.cc +++ b/selfdrive/common/util.cc @@ -1,5 +1,7 @@ #include "selfdrive/common/util.h" +#include + #include #include #include @@ -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) {