fs.c 2.0 KB

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