ysfx_utils_fts.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2021 Jean Pierre Cimalando
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // SPDX-License-Identifier: Apache-2.0
  16. //
  17. #if !defined(_WIN32) && !defined(YSFX_NO_FTS)
  18. // fts lacks large file support in glibc < 2.23
  19. #if defined(YSFX_FTS_LACKS_LFS_SUPPORT)
  20. # undef _FILE_OFFSET_BITS
  21. #endif
  22. #include "ysfx_utils.hpp"
  23. #include <fts.h>
  24. #include <string>
  25. #include <cstring>
  26. namespace ysfx {
  27. void visit_directories(const char *rootpath, bool (*visit)(const std::string &, void *), void *data)
  28. {
  29. char *argv[] = {(char *)rootpath, nullptr};
  30. #if !defined(__FreeBSD__)
  31. using compar_arg_t = const FTSENT **;
  32. #else
  33. using compar_arg_t = const FTSENT *const *;
  34. #endif
  35. auto compar = [](compar_arg_t a, compar_arg_t b) -> int {
  36. return strcmp((*a)->fts_name, (*b)->fts_name);
  37. };
  38. FTS *fts = fts_open(argv, FTS_NOCHDIR|FTS_PHYSICAL, +compar);
  39. if (!fts)
  40. return;
  41. auto fts_cleanup = defer([fts]() { fts_close(fts); });
  42. std::string pathbuf;
  43. pathbuf.reserve(1024);
  44. while (FTSENT *ent = fts_read(fts)) {
  45. if (ent->fts_info == FTS_D) {
  46. pathbuf.assign(ent->fts_path);
  47. pathbuf.push_back('/');
  48. if (!visit(pathbuf, data))
  49. return;
  50. }
  51. }
  52. }
  53. } // namespace ysfx
  54. #endif // !defined(_WIN32) && !defined(YSFX_NO_FTS)