copendir
函数用于打开一个目录流,以便后续使用 readdir
函数读取目录中的条目。要遍历目录结构,你需要递归地处理子目录。以下是一个示例代码,展示了如何使用 copendir
和 readdir
遍历目录结构:
#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 = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
list_directory_contents(full_path); // 递归调用以处理子目录
} else {
printf("File: %s\n", 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;
}
opendir
打开指定路径的目录。readdir
读取目录中的每个条目。.
)和父目录(..
)。snprintf
构建条目的完整路径。stat
获取文件信息,并检查是否为目录。list_directory_contents
处理子目录。closedir
关闭目录流。编译并运行程序,传入要遍历的目录路径作为参数:
gcc -o listdir listdir.c
./listdir /path/to/directory
这个程序会递归地遍历指定目录及其所有子目录,并打印出每个文件和目录的完整路径。