Created
January 20, 2023 07:15
-
-
Save Blizzardo1/ec37e5b29373f7a2a469b1e94068ebe4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <dirent.h> | |
#include <string.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
/** | |
* @brief Function to recursively scan a directory and print the file names and the number of hard links | |
* | |
* @param dir_name The directory to scan | |
*/ | |
void scan_directory(const char* dir_name) { | |
DIR* dir = opendir(dir_name); | |
struct dirent* entry; | |
struct stat statbuf; | |
char path[1024]; | |
// If the directory cannot be opened, then print an error message and return | |
if (dir == NULL) { | |
printf("Cannot open directory: %s\n", dir_name); | |
return; | |
} | |
while ((entry = readdir(dir)) != NULL) { | |
// Compare (If the directory names are . for the current directory or .. for the parent directory), then continue | |
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) | |
continue; | |
// Create a path to the file | |
snprintf(path, sizeof(path), "%s/%s", dir_name, entry->d_name); | |
// Get the file information | |
if (lstat(path, &statbuf) == -1) { | |
// If you are unable to get the file information, then print an error message and continue | |
perror("lstat error"); | |
continue; | |
} | |
// If the file is a regular file and has more than one hard link, then print the file name and the number of hard links | |
if (S_ISREG(statbuf.st_mode) && statbuf.st_nlink >= 2) { | |
printf("File: %s has %ld hard links\n", path, statbuf.st_nlink); | |
// Code to list all file names that point to this file | |
} | |
// If the file is a directory, then recursively call the scan_directory function | |
else if (S_ISDIR(statbuf.st_mode)) { | |
scan_directory(path); | |
} | |
} | |
// Close the directory | |
closedir(dir); | |
} | |
/** | |
* @brief Main function to call the scan_directory function | |
* | |
* @return int EXIT_SUCCESS on exit | |
*/ | |
int main() { | |
// Call the scan_directory function to scan the current directory | |
scan_directory("/"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment