在Linux中,readdir
函数用于读取目录中的条目。如果你想要实现文件过滤,可以在调用readdir
之后对返回的dirent
结构体中的d_name
字段进行检查,根据需要过滤掉不需要的文件或目录。
以下是一个简单的示例,展示了如何使用readdir
函数读取目录并过滤掉所有非普通文件(例如目录、符号链接等):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
int is_regular_file(const char *path) {
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISREG(path_stat.st_mode);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (is_regular_file(entry->d_name)) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
在这个示例中,我们首先定义了一个辅助函数is_regular_file
,它接受一个文件路径作为参数,并使用stat
函数获取文件的元数据。然后,我们检查文件的类型是否为普通文件(S_ISREG
宏)。
在main
函数中,我们打开指定的目录,并使用readdir
函数读取目录中的条目。对于每个条目,我们调用is_regular_file
函数检查它是否为普通文件。如果是,我们将其名称打印到屏幕上。
要编译此程序,请将其保存为list_files.c
,然后运行以下命令:
gcc -o list_files list_files.c
现在,你可以使用这个程序列出指定目录中的所有普通文件:
./list_files /path/to/directory
请注意,这个示例仅用于演示目的,实际应用中可能需要根据需求进行更多的错误处理和功能扩展。