2 * Copyright (c) Meta Platforms, Inc. and affiliates.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
11 #include "utils/Portability.h"
12 #include "utils/Range.h"
18 #include <system_error>
20 // A small subset of `std::filesystem`.
21 // `std::filesystem` should be a drop in replacement.
22 // See https://en.cppreference.com/w/cpp/filesystem for documentation.
26 // using file_status = ... causes gcc to emit a false positive warning
28 typedef struct ::_stat64 file_status;
30 typedef struct ::stat file_status;
33 /// https://en.cppreference.com/w/cpp/filesystem/status
34 inline file_status status(StringPiece path, std::error_code& ec) noexcept {
37 const auto error = ::_stat64(path.data(), &status);
39 const auto error = ::stat(path.data(), &status);
42 ec.assign(errno, std::generic_category());
49 /// https://en.cppreference.com/w/cpp/filesystem/is_regular_file
50 inline bool is_regular_file(file_status status) noexcept {
52 return S_ISREG(status.st_mode);
53 #elif !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
54 return (status.st_mode & S_IFMT) == S_IFREG;
56 static_assert(false, "No POSIX stat() support.");
60 /// https://en.cppreference.com/w/cpp/filesystem/is_regular_file
61 inline bool is_regular_file(StringPiece path, std::error_code& ec) noexcept {
62 return is_regular_file(status(path, ec));
65 /// https://en.cppreference.com/w/cpp/filesystem/is_directory
66 inline bool is_directory(file_status status) noexcept {
68 return S_ISDIR(status.st_mode);
69 #elif !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
70 return (status.st_mode & S_IFMT) == S_IFDIR;
72 static_assert(false, "NO POSIX stat() support.");
76 /// https://en.cppreference.com/w/cpp/filesystem/is_directory
77 inline bool is_directory(StringPiece path, std::error_code& ec) noexcept {
78 return is_directory(status(path, ec));
81 /// https://en.cppreference.com/w/cpp/filesystem/file_size
82 inline std::uintmax_t file_size(
84 std::error_code& ec) noexcept {
85 auto stat = status(path, ec);
87 return std::numeric_limits<uintmax_t>::max();
89 if (!is_regular_file(stat)) {
90 ec.assign(ENOTSUP, std::generic_category());
91 return std::numeric_limits<uintmax_t>::max();