在 CentOS(或者说 Linux C 语言环境)里,readdir() 本身不能过滤,它只是把目录里的每一项都读出来。
过滤要在你自己的代码里做。
下面按常见需求给你几种做法。
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
#include <sys/stat.h>
while ((entry = readdir(dir)) != NULL) {
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode))
printf("[DIR] %s\n", entry->d_name);
else if (S_ISREG(st.st_mode))
printf("[FILE] %s\n", entry->d_name);
}
.txt)#include <string.h>
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".txt"))
printf("%s\n", entry->d_name);
}
if (strncmp(entry->d_name, "log", 3) == 0)
printf("%s\n", entry->d_name);
scandir 可以直接传过滤函数:
int filter(const struct dirent *e) {
return strncmp(e->d_name, "test", 4) == 0;
}
struct dirent **namelist;
int n = scandir(".", &namelist, filter, alphasort);
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
ls | grep txt
如果你能说清楚:
我可以直接给你一段可编译的代码。