在 Linux 中,使用 opendir()
、readdir()
和 closedir()
函数可以遍历目录结构。下面是一个简单的示例,展示了如何使用这些函数遍历目录结构:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void traverse_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
// 获取文件的详细信息
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
// 如果是目录,则递归遍历
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
traverse_directory(full_path);
}
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
traverse_directory(argv[1]);
return 0;
}
这个程序接受一个目录路径作为参数,并递归地遍历该目录及其子目录。对于每个文件和目录,它将打印其名称。请注意,这个程序不会处理符号链接,也不会检查访问权限。在实际应用中,你可能需要根据需求对这些方面进行处理。