I'm trying to delete all dangling links from dir Recursively, but on each link i got "lstat: No such file or directory".
void deletelinks(char *name, int indent)
{
DIR *dir;
FILE *a;
struct stat sb;
char *buf;
ssize_t nbytes, bufsiz;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path[1024];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
// printf("%*s[%s]\n", indent, "", entry->d_name);
deletelinks(path, indent + 2);
} else {
if(entry->d_type == DT_LNK){
if (lstat(("%s/%s", name, entry->d_name), &sb) == -1) {
printf("%s/%s", name, entry->d_name);
perror("lstat");
exit(EXIT_FAILURE);
}
bufsiz = sb.st_size + 1;
if (sb.st_size == 0)
bufsiz = PATH_MAX;
buf = malloc(bufsiz);
if (buf == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
nbytes = readlink(("%s%s", name, entry->d_name), buf, bufsiz);
if (nbytes == -1) {
perror("readlink");
exit(EXIT_FAILURE);
}
a=fopen(("%s/%*s",name, (int) nbytes, buf), "r");
if(a==NULL){
printf("%s/%*s\n",name, (int) nbytes, buf);
}
}
}
}
closedir(dir);
}
I want this function to delete all dangling or broken links in dir. This func successfully find all links recursevly, but it cant recognize if it dagling or not, because i have an error "lstat: No such file or directory"