00001 #include <sys/types.h>
00002 #include <sys/stat.h>
00003 #include <dirent.h>
00004 #include <errno.h>
00005 #include <string.h>
00006 #include <alloca.h>
00007 #include <stdio.h>
00008 #include "file_tools.h"
00009
00010 std::string RemoveDir(const char* path)
00011 {
00012 DIR* cwd = opendir(path);
00013 if(cwd == NULL)
00014 return "Couldn't opendir " + std::string(path) + " : " + std::string(strerror(errno));
00015
00016 struct dirent* dir;
00017
00018 while((dir = readdir(cwd)) != NULL)
00019 {
00020 if(!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
00021 continue;
00022
00023 unsigned int path_len = strlen(path) + strlen(dir->d_name) + 1;
00024 char* full_path = (char*)alloca(path_len + 1);
00025 full_path[path_len] = '\0';
00026 snprintf(full_path, path_len, "%s/%s", path, dir->d_name);
00027
00028 if(dir->d_type == 8)
00029 {
00030 if(unlink(full_path) == -1)
00031 {
00032 closedir(cwd);
00033 return "Couldn't remove file " + std::string(full_path) + " : " + std::string(strerror(errno));
00034 }
00035 }
00036 else
00037 if(dir->d_type == 4)
00038 {
00039 std::string err = RemoveDir(full_path);
00040 if(err != "")
00041 return err;
00042 }
00043 }
00044 closedir(cwd);
00045 if(rmdir(path) == -1)
00046 return "Couldn't remove directory " + std::string(path) + " : " + std::string(strerror(errno));
00047 return "";
00048 }