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

* fix bug

* add test case
pull/21890/head
Dean Lee 2021-08-09 17:56:45 +08:00 committed by GitHub
parent aa89bb727e
commit 3a7959b5ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 2 deletions

View File

@ -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);
}

View File

@ -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) {