Added an inefficient listing for entries
This commit is contained in:
74
src/entry.c
74
src/entry.c
@@ -8,6 +8,7 @@
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <libgen.h>
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
bool is_entry_id_valid(const char* entry_id) {
|
||||
@@ -230,6 +231,79 @@ Result remove_entry(const char* entry_id) {
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
Result list_entries(char*** out_entries) {
|
||||
*out_entries = malloc(sizeof(char*));
|
||||
if (*out_entries == NULL) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to allocate memory for the entries.");
|
||||
return OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
(*out_entries)[0] = NULL;
|
||||
|
||||
// Open the directory
|
||||
DIR* dir = opendir(ENTRY_POOL_DIR);
|
||||
if (dir == NULL) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to open the directory '%s' (%s).", ENTRY_POOL_DIR, strerror(errno));
|
||||
return FAILURE;
|
||||
}
|
||||
|
||||
// Read the directory
|
||||
int entry_count = 0;
|
||||
|
||||
struct dirent* entry;
|
||||
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
// Skip the current and parent directories
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
||||
continue;
|
||||
|
||||
// Check that the entry exists
|
||||
bool exists;
|
||||
Result result = entry_exists(entry->d_name, &exists);
|
||||
if (result != SUCCESS || !exists)
|
||||
continue;
|
||||
|
||||
// Reallocate the entries array
|
||||
// TODO: More efficient reallocation
|
||||
char** new_entries = realloc(*out_entries, (entry_count + 2) * sizeof(char*));
|
||||
if (new_entries == NULL) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to allocate memory for the entries.");
|
||||
closedir(dir);
|
||||
|
||||
for (int i = 0; i < entry_count; i++)
|
||||
free((*out_entries)[i]);
|
||||
free(*out_entries);
|
||||
|
||||
return OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
*out_entries = new_entries;
|
||||
|
||||
// Copy the entry name
|
||||
(*out_entries)[entry_count] = strdup(entry->d_name);
|
||||
if ((*out_entries)[entry_count] == NULL) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to allocate memory for the entry name.");
|
||||
closedir(dir);
|
||||
|
||||
for (int i = 0; i < entry_count; i++)
|
||||
free((*out_entries)[i]);
|
||||
free(*out_entries);
|
||||
|
||||
return OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
// Null-terminate the array
|
||||
(*out_entries)[entry_count + 1] = NULL;
|
||||
|
||||
entry_count++;
|
||||
}
|
||||
|
||||
// Close the directory
|
||||
closedir(dir);
|
||||
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
Result reset_entry(const char* entry_id) {
|
||||
// Check that it exists
|
||||
bool exists;
|
||||
|
Reference in New Issue
Block a user