Added a function to delete a directory
This commit is contained in:
65
src/utils.c
65
src/utils.c
@@ -9,6 +9,7 @@
|
||||
#include <dirent.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
char* format(const char* fmt, ...) {
|
||||
va_list args;
|
||||
@@ -269,3 +270,67 @@ int execute(char** stdout_buffer, char** stderr_buffer, const char* file, ...) {
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
|
||||
}
|
||||
|
||||
bool delete_directory(const char* directory) {
|
||||
// Open the directory
|
||||
DIR* dir = opendir(directory);
|
||||
if (dir == NULL) {
|
||||
log_msg(LOG_ERROR, "Failed to open directory '%s'.", directory);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Iterate over the directory entries
|
||||
struct dirent* entry;
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
// Skip . and ..
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
||||
continue;
|
||||
|
||||
// Combine the directory path with the entry name
|
||||
char* entry_path = format("%s/%s", directory, entry->d_name);
|
||||
if (entry_path == NULL) {
|
||||
log_msg(LOG_ERROR, "Failed to allocate memory for the entry path.");
|
||||
closedir(dir);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the entry is a directory
|
||||
struct stat statbuf;
|
||||
int result = stat(entry_path, &statbuf);
|
||||
if (result != 0) {
|
||||
log_msg(LOG_ERROR, "Failed to get information about entry '%s'.", entry_path);
|
||||
free(entry_path);
|
||||
closedir(dir);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (S_ISDIR(statbuf.st_mode)) {
|
||||
// Delete the directory
|
||||
if (!delete_directory(entry_path)) {
|
||||
free(entry_path);
|
||||
closedir(dir);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Delete the file
|
||||
if (unlink(entry_path) != 0) {
|
||||
log_msg(LOG_ERROR, "Failed to delete entry '%s'.", entry_path);
|
||||
free(entry_path);
|
||||
closedir(dir);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
free(entry_path);
|
||||
}
|
||||
|
||||
// Close the directory
|
||||
closedir(dir);
|
||||
|
||||
// Delete the directory
|
||||
if (rmdir(directory) != 0) {
|
||||
log_msg(LOG_ERROR, "Failed to delete directory '%s'.", directory);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
Reference in New Issue
Block a user