This is my function that uses recursion to recursively delete a directory. I like my way of skipping entries .
and ..
.
But should I be casting the name lengths to unsigned int
because I am quite sure there will not be file paths longer than 4 gigacharacters? Or is storing the result of strlen
in any type other than size_t
bad practice?
Any other comments here?
Also is using VLAs in a recursive function risky, could it cause a stack overflow error? Is the VLA OK, or should I just use malloc()
(I vehemently refuse to simply use a fixed size buffer that should be big enough, like )?char Entry[1024]
int Remove(const char *const Object) {
DIR *const Dir = opendir(Object);
if (Dir) {
struct dirent *Dirent;
const unsigned int Len = (unsigned int)strlen(Object);
while ((Dirent = readdir(Dir))) {
const char *const Name = Dirent->d_name;
const unsigned int NameLen = (unsigned int)strlen(Name);
if (Name[0] == '.' && (NameLen == 1 || (Name[1] == '.' && NameLen == 2))) {
continue;
}
char Entry[Len+NameLen+2], *const CurrPtr = memcpy(Entry, Object, Len)+Len;
*CurrPtr = '/';
*(char *)(memcpy(CurrPtr+1, Name, NameLen)+NameLen) = 0;
if ((Dirent->d_type == DT_DIR? Remove : remove)(Entry)) {
return -1;
}
}
if (closedir(Dir)) {
return -1;
}
}
return remove(Object);
}
d_type
is an optional optimization, and can be DT_UNKNOWN. See Checking if a dir. entry returned by readdir is a directory, link or file. dent->d_type isn't showing the type \$\endgroup\$