在 CentOS 系统中,你可以使用 readdir 函数来遍历目录树
首先,确保你已经安装了必要的开发工具和库。在 CentOS 上,你可以使用以下命令安装:
sudo yum groupinstall "Development Tools"
sudo yum install glibc-devel
接下来,创建一个名为 traverse_directory.c 的 C 文件,并添加以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void traverse_directory(const char *path);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
traverse_directory(argv[1]);
return 0;
}
void traverse_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char fullpath[PATH_MAX];
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (lstat(fullpath, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", fullpath);
traverse_directory(fullpath);
} else {
printf("File: %s\n", fullpath);
}
}
closedir(dir);
}
保存文件后,使用以下命令编译代码:
gcc -o traverse_directory traverse_directory.c
现在,你可以运行生成的可执行文件 traverse_directory 并传递一个目录路径作为参数,例如:
./traverse_directory /path/to/your/directory
这将遍历指定的目录树并打印所有文件和子目录。