Skip to content

Commit 223a55b

Browse files
cblichmanncopybara-github
authored andcommitted
Windows: Make FileExists() return false on directories
This brings the behavior in line with macOS and Linux. PiperOrigin-RevId: 375066708 Change-Id: I2ee86913bbc6c45a8ed0ec5a07a5a2c763ce43c9
1 parent 44d5b5f commit 223a55b

1 file changed

Lines changed: 14 additions & 12 deletions

File tree

util/filesystem.cc

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,9 @@ std::string ReplaceFileExtension(absl::string_view path,
213213
#ifndef _WIN32
214214
namespace {
215215

216-
absl::StatusOr<mode_t> GetFileMode(absl::string_view path) {
216+
absl::StatusOr<mode_t> GetFileMode(const std::string& path) {
217217
struct stat file_info;
218-
std::string path_copy(path);
219-
if (stat(path_copy.c_str(), &file_info) == -1) {
218+
if (stat(path.c_str(), &file_info) == -1) {
220219
switch (errno) {
221220
case EACCES:
222221
case ENOENT:
@@ -234,7 +233,7 @@ absl::StatusOr<mode_t> GetFileMode(absl::string_view path) {
234233
#endif
235234

236235
absl::StatusOr<int64_t> GetFileSize(absl::string_view path) {
237-
std::ifstream stream(std::string(path), std::ifstream::ate);
236+
std::ifstream stream(std::string(path), std::ios::ate);
238237
auto size = static_cast<int64_t>(stream.tellg());
239238
if (stream) {
240239
return size;
@@ -243,22 +242,25 @@ absl::StatusOr<int64_t> GetFileSize(absl::string_view path) {
243242
}
244243

245244
bool FileExists(absl::string_view path) {
246-
#ifdef _WIN32
247245
std::string path_copy(path);
248-
return PathFileExists(path_copy.c_str()) == TRUE;
246+
#ifdef _WIN32
247+
DWORD attr = GetFileAttributes(path_copy.c_str());
248+
return (attr != INVALID_FILE_ATTRIBUTES) &&
249+
!(attr & FILE_ATTRIBUTE_DIRECTORY);
249250
#else
250-
auto mode_or = GetFileMode(path);
251-
return mode_or.ok() ? S_ISREG(mode_or.value()) : false;
251+
auto mode = GetFileMode(path_copy);
252+
return mode.ok() ? S_ISREG(*mode) : false;
252253
#endif
253254
}
254255

255256
bool IsDirectory(absl::string_view path) {
256-
#ifdef _WIN32
257257
std::string path_copy(path);
258-
return PathIsDirectory(path_copy.c_str()) == FILE_ATTRIBUTE_DIRECTORY;
258+
#ifdef _WIN32
259+
DWORD attr = GetFileAttributes(path_copy.c_str());
260+
return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
259261
#else
260-
auto mode_or = GetFileMode(path);
261-
return mode_or.ok() ? S_ISDIR(mode_or.value()) : false;
262+
auto mode = GetFileMode(path_copy);
263+
return mode.ok() ? S_ISDIR(*mode) : false;
262264
#endif
263265
}
264266

0 commit comments

Comments
 (0)