在Linux中,可以使用opendir()
、readdir()
和closedir()
函數來實現目錄的遞歸遍歷。下面是一個簡單的示例代碼,展示了如何使用這些函數來遞歸遍歷一個目錄及其子目錄中的所有文件和文件夾:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
// Skip current and parent directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct full path
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// Get file/directory information
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// Print the name of the file/directory
printf("%s\n", full_path);
// If it's a directory, recurse into it
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
這個程序接受一個命令行參數,即要遍歷的目錄路徑。它會打開目錄,讀取其中的條目,并打印出每個文件和子目錄的完整路徑。如果遇到子目錄,它會遞歸地調用list_directory_contents()
函數來遍歷子目錄中的內容。
要編譯這個程序,你可以使用gcc
:
gcc -o listdir listdir.c
然后運行它,傳入你想要遍歷的目錄路徑:
./listdir /path/to/directory
請注意,這個程序沒有處理符號鏈接,如果目錄中包含符號鏈接,可能會導致無限遞歸。此外,錯誤處理也比較簡單,實際使用時可能需要更詳細的錯誤檢查和處理。