obviating if the recursive function is well constructed or not, when i call the function on a directory Folder/file.txt. this code should delete file.txt, but when it reaches to
if (remove(actual->d_name) != 0 && rmdir(actual->d_name) != 0){
remove dont work, and i dont know for what…
void borrarrecursivo(DIR *directorio){ struct dirent *actual; while(((actual = readdir(directorio)) != NULL) && (actual->d_name) != NULL){ if ((strcmp(actual->d_name, ".") != 0) && (strcmp(actual->d_name, "..") != 0)){ if (remove(actual->d_name) != 0 && rmdir(actual->d_name) != 0){ DIR *siguiente; if ((siguiente = opendir(actual->d_name)) != NULL){ borrarrecursivo(siguiente); } } } } closedir(directorio); //} }//fin borrarrecursivo
Advertisement
Answer
Reading the man page on readdir
, it returns in d_name
a file name, not a complete path, but remove
and rmdir
expect a full path (or an entry relative to current working directory).
So with every recursive call of your function, you must construct a new path of where you currently are, and pass that in your recursive call. (I leave to you to change your code to achieve this.)
Note: you also assume that if you can neither remove, nor rmdir, it must be a directory and you want to recurse. But it does not have to be a directory. You should check the d_type
field.
Note: the man page for remove says it calls rmdir if the name is a directory. Calling rmdir is thus unnecessary.