I made this function to recursively delete a directory and its contents, because using VLAs to concatenate paths is more susceptible to Stack Overflow and is probably slower.
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <string.h>
int SavesFD;
static int Recursive(const int File, const char *const Name) {
const int File0 = openat(File, Name, O_DIRECTORY);
if (File0 == -1)
return 1;
DIR *const Dir = fdopendir(File0);
if (!Dir)
return 1;
for (struct dirent *Dirent; (Dirent = readdir(Dir));)
if ((*Dirent->d_name != '.' || (Dirent->d_name[1] && *(uint16_t *)(Dirent->d_name+1) != '.')) && (Dirent->d_type == DT_DIR ? Recursive(File0, Dirent->d_name) : unlinkat(File0, Dirent->d_name, 0)))
return 1;
return closedir(Dir) || unlinkat(File, Name, AT_REMOVEDIR);
}
void DeleteSave(const char *const Name) {
if (Recursive(SavesFD, Name))
perror(Name);
}
I believe my code is efficient but not very readable or easy to comprehend; is this an example of premature micro-optimization?
And also, if I am repeatedly accessing the value of Dirent->d_name
or Dirent->d_name[1]
should I consider storing these in variables?
..foo
(that is starting with 2 or more dots)? \$\endgroup\$