Browse Source

faux.base: Function faux_rm()

Serj Kalichev 4 years ago
parent
commit
731a69b24e
3 changed files with 58 additions and 3 deletions
  1. 2 2
      faux/base/Makefile.am
  2. 52 0
      faux/base/fs.c
  3. 4 1
      faux/faux.h

+ 2 - 2
faux/base/Makefile.am

@@ -1,4 +1,4 @@
 libfaux_la_SOURCES += \
 	faux/base/mem.c \
-	faux/base/io.c
-
+	faux/base/io.c \
+	faux/base/fs.c

+ 52 - 0
faux/base/fs.c

@@ -0,0 +1,52 @@
+/** @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>
+
+/** @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) {
+
+	struct stat statbuf = {};
+	DIR *dir = NULL;
+	struct dirent *dir_entry = NULL;
+
+	assert(path);
+	if (!path)
+		return -1;
+
+	if (lstat(path, &statbuf) < 0)
+		return -1;
+
+	// Common file (not dir)
+	if (!S_ISDIR(statbuf.st_mode))
+		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);
+}

+ 4 - 1
faux/faux.h

@@ -64,12 +64,15 @@ void *faux_malloc(size_t size);
 void faux_bzero(void *ptr, size_t size);
 void *faux_zmalloc(size_t size);
 
-// IO
+// I/O
 ssize_t faux_write(int fd, const void *buf, size_t n);
 ssize_t faux_read(int fd, void *buf, size_t n);
 ssize_t faux_write_block(int fd, const void *buf, size_t n);
 size_t faux_read_block(int fd, void *buf, size_t n);
 
+// Filesystem
+int faux_rm(const char *path);
+
 C_DECL_END
 
 #endif /* _faux_types_h */