fs.hpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #pragma once
  2. #include <sys/stat.h>
  3. #include <string>
  4. #include <dirent.h>
  5. #include "utils/utils.h"
  6. using namespace std;
  7. namespace fs {
  8. inline bool existsNothing(string filePath) {
  9. struct stat buffer;
  10. return stat(filePath.c_str(), &buffer) != 0;
  11. }
  12. inline bool existsAnything(string filePath) {
  13. struct stat buffer;
  14. return stat(filePath.c_str(), &buffer) == 0;
  15. }
  16. inline bool existsFile(string filePath) {
  17. struct stat buffer;
  18. if (stat(filePath.c_str(), &buffer) == 0) {
  19. return S_ISREG(buffer.st_mode);
  20. }
  21. return false;
  22. }
  23. inline bool deleteFile(string filePath) {
  24. return ::remove(filePath.c_str()) == 0;
  25. }
  26. inline bool existsDirectory(string filePath) {
  27. struct stat buffer;
  28. if (stat(filePath.c_str(), &buffer) == 0) {
  29. return !S_ISREG(buffer.st_mode);
  30. }
  31. return false;
  32. }
  33. inline vector<string> contentsOfDirectory(string filePath) {
  34. DIR *pDir;
  35. struct dirent* ptr;
  36. vector<string> ret;
  37. if (!(pDir = opendir(filePath.c_str()))){
  38. return ret;
  39. }
  40. while ((ptr = readdir(pDir)) != 0) {
  41. if (::strlen(ptr->d_name) > 0) {
  42. if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0 && ptr->d_name[0] != '.') {
  43. ret.push_back(ptr->d_name);
  44. }
  45. }
  46. }
  47. closedir(pDir);
  48. return ret;
  49. }
  50. }