在 CentOS 系统中,可以使用 readdir
函数来遍历文件系统
sudo yum groupinstall "Development Tools"
sudo yum install glibc-devel
traverse.c
的 C 语言源文件,并添加以下代码:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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 = 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 path_stat;
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
traverse_directory(full_path);
} else {
printf("%s\n", full_path);
}
}
closedir(dir);
}
这段代码定义了一个名为 traverse_directory
的递归函数,它会遍历指定路径下的所有文件和目录,并将文件的完整路径打印到屏幕上。
gcc
编译源代码:gcc -o traverse traverse.c
./traverse /path/to/directory
程序将递归地遍历指定目录及其子目录,并打印所有文件的完整路径。
注意:在实际使用中,请确保你有足够的权限访问要遍历的目录。