123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- /** @file fs.c
- * @brief Enchanced base filesystem operations.
- */
- #include <stdlib.h>
- #include <unistd.h>
- #include <assert.h>
- #include <errno.h>
- #include <stdio.h>
- #include <string.h>
- #include <dirent.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include "faux/str.h"
- /** @brief If given path is directory.
- *
- * @param [in] path Filesystem path.
- * @return 0 - success, < 0 on error.
- */
- bool_t faux_isdir(const char *path)
- {
- struct stat statbuf = {};
- assert(path);
- if (!path)
- return BOOL_FALSE;
- if (lstat(path, &statbuf) < 0)
- return BOOL_FALSE;
- if (S_ISDIR(statbuf.st_mode))
- return BOOL_TRUE;
- return BOOL_FALSE;
- }
- /** @brief Removes filesystem objects recursively.
- *
- * Function can remove file or directory (recursively).
- *
- * @param [in] path File/directory name.
- * @return 0 - success, < 0 on error.
- */
- int faux_rm(const char *path)
- {
- DIR *dir = NULL;
- struct dirent *dir_entry = NULL;
- assert(path);
- if (!path)
- return -1;
- // Common file (not dir)
- if (!faux_isdir(path))
- return unlink(path);
- // Directory
- if ((dir = opendir(path)) == NULL)
- return -1;
- while ((dir_entry = readdir(dir))) {
- if (!strcmp(dir_entry->d_name, ".") ||
- !strcmp(dir_entry->d_name, ".."))
- continue;
- faux_rm(dir_entry->d_name);
- }
- closedir(dir);
- return rmdir(path);
- }
- /** @brief Expand tilde within path due to HOME env var.
- *
- * If first character of path is tilde then expand it to value of
- * environment variable HOME. If tilde is not the first character or
- * HOME is not defined then return copy of original path.
- *
- * @warning The resulting string must be freed by faux_str_free() later.
- *
- * @param [in] path Path to expand.
- * @return Expanded string or NULL on error.
- */
- char *faux_expand_tilde(const char *path)
- {
- char *home_dir = getenv("HOME");
- char *result = NULL;
- assert(path);
- if (!path)
- return NULL;
- // Tilde can be the first character only to be expanded
- if (home_dir && (path[0] == '~'))
- result = faux_str_sprintf("%s%s", home_dir, &path[1]);
- else
- result = faux_str_dup(path);
- return result;
- }
|