在 CentOS(Linux) 下使用 readdir 读取目录时,readdir 本身并不会过滤文件,它只是逐个返回目录项(struct dirent)。
过滤逻辑需要你在代码里自己实现。
下面分几种常见情况说明。
readdir 的基本方式(C 语言)#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;
}
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
if (entry->d_type == DT_REG) {
printf("%s\n", entry->d_name);
}
常见
d_type:
DT_REG:普通文件DT_DIR:目录DT_LNK:符号链接⚠️ 注意:d_type 在某些文件系统(如 NFS)上可能不可用,需用 stat()。
stat 精确判断文件类型(推荐)#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode)) {
// 普通文件
}
.log)if (strstr(entry->d_name, ".log")) {
printf("%s\n", entry->d_name);
}
或更严谨:
size_t len = strlen(entry->d_name);
if (len > 4 && strcmp(entry->d_name + len - 4, ".log") == 0) {
printf("%s\n", entry->d_name);
}
if (st.st_mode & S_IRUSR) { // 当前用户可读
}
if (st.st_size > 1024) { // 大于 1KB
}
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
struct stat st;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode) &&
strstr(entry->d_name, ".txt")) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
ls *.log
或
find . -maxdepth 1 -type f -name "*.log"
如果你能说明:
我可以给你更精确的示例。