在 CentOS 系统中,可以使用 readdir
函数来遍历目录结构。readdir
是一个 C 语言库函数,用于读取目录中的条目。以下是一个简单的示例,展示了如何使用 readdir
遍历目录结构:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void traverse_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
char full_path[1024];
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) {
continue;
}
printf("Directory: %s\n", full_path);
traverse_directory(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 1;
}
traverse_directory(argv[1]);
return 0;
}
这个程序接受一个目录路径作为参数,并递归地遍历该目录及其子目录。对于每个目录和文件,它将打印出完整的路径。
要编译此程序,请将其保存为 traverse_directory.c
,然后在终端中运行以下命令:
gcc -o traverse_directory traverse_directory.c
现在,您可以使用以下命令运行程序,其中 <directory>
是要遍历的目录路径:
./traverse_directory <directory>
请注意,这个示例仅适用于 C 语言。如果您需要在其他编程语言中实现类似的功能,请查阅相应语言的文档。