在 CentOS 系统中,你可以使用 readdir
函数来遍历文件系统。readdir
是一个用于读取目录内容的函数,通常与 opendir
和 closedir
一起使用。下面是一个简单的示例,展示了如何使用这些函数遍历当前目录下的所有文件和子目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
// 打开当前目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
// 遍历目录中的每个条目
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// 关闭目录
closedir(dir);
return 0;
}
要编译此程序,请将其保存为 list_directory.c
,然后在终端中运行以下命令:
gcc list_directory.c -o list_directory
最后,运行编译后的程序:
./list_directory
这将显示当前目录下的所有文件和子目录。如果你想遍历其他目录,只需将 opendir(".")
中的参数更改为所需目录的路径即可。