fs.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #include "faux/str.h"
  15. /** @brief Removes filesystem objects recursively.
  16. *
  17. * Function can remove file or directory (recursively).
  18. *
  19. * @param [in] path File/directory name.
  20. * @return 0 - success, < 0 on error.
  21. */
  22. int faux_rm(const char *path)
  23. {
  24. struct stat statbuf = {};
  25. DIR *dir = NULL;
  26. struct dirent *dir_entry = NULL;
  27. assert(path);
  28. if (!path)
  29. return -1;
  30. if (lstat(path, &statbuf) < 0)
  31. return -1;
  32. // Common file (not dir)
  33. if (!S_ISDIR(statbuf.st_mode))
  34. return unlink(path);
  35. // Directory
  36. if ((dir = opendir(path)) == NULL)
  37. return -1;
  38. while ((dir_entry = readdir(dir))) {
  39. if (!strcmp(dir_entry->d_name, ".") ||
  40. !strcmp(dir_entry->d_name, ".."))
  41. continue;
  42. faux_rm(dir_entry->d_name);
  43. }
  44. closedir(dir);
  45. return rmdir(path);
  46. }
  47. /** @brief Expand tilde within path due to HOME env var.
  48. *
  49. * If first character of path is tilde then expand it to value of
  50. * environment variable HOME. If tilde is not the first character or
  51. * HOME is not defined then return copy of original path.
  52. *
  53. * @warning The resulting string must be freed by faux_str_free() later.
  54. *
  55. * @param [in] path Path to expand.
  56. * @return Expanded string or NULL on error.
  57. */
  58. char *faux_expand_tilde(const char *path)
  59. {
  60. char *home_dir = getenv("HOME");
  61. char *result = NULL;
  62. assert(path);
  63. if (!path)
  64. return NULL;
  65. // Tilde can be the first character only to be expanded
  66. if (home_dir && (path[0] == '~'))
  67. result = faux_str_sprintf("%s%s", home_dir, &path[1]);
  68. else
  69. result = faux_str_dup(path);
  70. return result;
  71. }