From c61bb864c026d26a393f2a09c82de9bbc5043c6f Mon Sep 17 00:00:00 2001 From: Christian C Date: Tue, 4 Mar 2025 19:10:07 -0800 Subject: Modularization --- src/lib/dir.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/lib/dir.c (limited to 'src/lib/dir.c') diff --git a/src/lib/dir.c b/src/lib/dir.c new file mode 100644 index 0000000..150d5bf --- /dev/null +++ b/src/lib/dir.c @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include + +//----------------------------------------------- +// Is directory +bool_t is_directory(char* dirname) { + struct stat st; + if (stat(dirname, &st) == 0) { + if (S_ISDIR(st.st_mode)) { + return TRUE; + } + } + return FALSE; +} + +//----------------------------------------------- +// List directory +char** lsdir(char* dirname) { + DIR *d; + struct dirent *dir; + d = opendir(dirname); + char** file_names = (char**)malloc(sizeof(char*)); + if (!file_names) { + return NULL; + } + file_names[0] = NULL; + size_t file_count = 0; + if (d) { + while ((dir = readdir(d)) != NULL) { + if (dir->d_type == DT_REG) { + // When a regular file is reached + /// Create space for it in the list + file_names = realloc(file_names, (file_count+1+1)*sizeof(char*)); + /// Create space for the name + file_names[file_count] = calloc(strlen(dir->d_name)+1, sizeof(char)); + /// Copy the name + strcpy(file_names[file_count], dir->d_name); + /// Mark the end of the file list with a NULL entry + file_names[++file_count] = NULL; + } + } + return file_names; + } + return NULL; +} + -- cgit v1.2.1