fs.c 1014 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /** @file fs.c
  2. * @brief Enchanced base filesystem operations.
  3. */
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <assert.h>
  7. #include <errno.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <dirent.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14. /** @brief Removes filesystem objects recursively.
  15. *
  16. * Function can remove file or directory (recursively).
  17. *
  18. * @param [in] path File/directory name.
  19. * @return 0 - success, < 0 on error.
  20. */
  21. int faux_rm(const char *path) {
  22. struct stat statbuf = {};
  23. DIR *dir = NULL;
  24. struct dirent *dir_entry = NULL;
  25. assert(path);
  26. if (!path)
  27. return -1;
  28. if (lstat(path, &statbuf) < 0)
  29. return -1;
  30. // Common file (not dir)
  31. if (!S_ISDIR(statbuf.st_mode))
  32. return unlink(path);
  33. // Directory
  34. if ((dir = opendir(path)) == NULL)
  35. return -1;
  36. while ((dir_entry = readdir(dir))) {
  37. if (!strcmp(dir_entry->d_name, ".") ||
  38. !strcmp(dir_entry->d_name, ".."))
  39. continue;
  40. faux_rm(dir_entry->d_name);
  41. }
  42. closedir(dir);
  43. return rmdir(path);
  44. }