在 CentOS 系统中,readdir 是一个用于读取目录内容的函数,通常在 C 语言编程中使用
以下是一个简单的示例,展示如何使用 readdir 函数读取目录内容并进行文件过滤:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
// 过滤掉 "." 和 ".." 目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 在这里添加你的文件过滤条件
// 例如,只显示 .txt 文件
if (strstr(entry->d_name, ".txt") != NULL) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
将上述代码保存为 list_files.c,然后使用以下命令编译:
gcc list_files.c -o list_files
现在,你可以运行编译后的程序,指定一个目录作为参数,它将列出该目录中所有以 .txt 结尾的文件:
./list_files /path/to/directory
你可以根据需要修改文件过滤条件。例如,如果你想列出所有以 .jpg 结尾的文件,只需将 strstr(entry->d_name, ".txt") != NULL 更改为 strstr(entry->d_name, ".jpg") != NULL。