// Recursively scan the currect directory // and ALL subdirectories and outputs a list // of all symlinks where the target does not exist // or could not be resolved // It should also print the total number of these dangling links #include #include #include #include #include #include #include // We will use recursion. int traverse(char *directory_path) { // Open current directory DIR *dirp = opendir(directory_path); if (dirp == NULL) { return 0 ; } int count = 0; struct dirent *entry; while ((entry = readdir(dirp)) != NULL){ if (strcmp(entry->d_name, ".") == 0) { continue; } if (strcmp(entry->d_name, "..") == 0) { continue; } //directory_path/entry->d_name int path_length = strlen(directory_path) + 1 + strlen(entry->d_name) + 1; char *path = malloc(path_length); snprintf(path, path_length,"%s/%s", directory_path, entry->d_name); //printf("full path of entry is %s\n", path); struct stat s; if (lstat(path, &s) != 0){ printf("lstat failed %s\n", path); free(path); continue; } if(S_ISLNK(s.st_mode)) { if (stat(path, &s) != 0){ printf("Dangling link: %s\n", path); count++; } //printf("LINK %s\n",entry->d_name); } else if (S_ISDIR(s.st_mode)){ count += traverse(path); } free(path); } closedir(dirp); return count; } // We will use recursion int main(void) { int count = traverse("."); printf("Total count %d\n", count); return 0; }