温馨提示×

linux readdir如何跳过指定文件

小樊
51
2026-10-17 07:35:27
栏目: 智能运维

在 Linux 下使用 readdir() 遍历目录时,如果你想跳过指定文件,通常的做法是在循环中对读取到的文件名进行判断,符合条件就 continue。

下面分几种常见情况说明。


一、使用 readdir() 跳过指定文件名(最常用)

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(".");
    if (!dir) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录和上级目录
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        // 跳过指定文件
        if (strcmp(entry->d_name, "skip.txt") == 0)
            continue;

        printf("file: %s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

✅ 这是标准、最通用的方式。


二、跳过多个指定文件

可以用数组或字符串匹配:

const char *skip_list[] = {"a.txt", "b.log", "temp"};
int skip_count = 3;

for (int i = 0; i < skip_count; i++) {
    if (strcmp(entry->d_name, skip_list[i]) == 0)
        goto next;
}

或更简洁:

if (strstr(entry->d_name, ".tmp"))
    continue;

三、跳过隐藏文件(以 . 开头)

if (entry->d_name[0] == '.')
    continue;

四、按文件类型跳过(如只处理普通文件)

if (entry->d_type == DT_DIR)
    continue;   // 跳过目录

⚠️ 注意:d_type 在某些文件系统(如 NFS)可能不可用,需配合 stat()。


五、结合 stat() 跳过特定类型/权限

struct stat st;
char path[256];
snprintf(path, sizeof(path), "./%s", entry->d_name);

if (stat(path, &st) == 0) {
    if (S_ISDIR(st.st_mode))
        continue;
}

六、更现代的替代方案(推荐)

如果允许使用 POSIX.1-2008:

readdir() + fstatat()(更安全)

或使用 nftw() / scandir()

scandir() 示例(自带过滤)

struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);

for (int i = 0; i < n; i++) {
    if (strcmp(namelist[i]->d_name, "skip.txt") == 0) {
        free(namelist[i]);
        continue;
    }
    printf("%s\n", namelist[i]->d_name);
    free(namelist[i]);
}
free(namelist);

总结

需求 方法
跳过指定文件名 strcmp() + continue
跳过隐藏文件 d_name[0] == '.'
跳过目录 d_type 或 stat()
灵活过滤 scandir()

如果你有具体跳过规则(如正则、后缀、权限),可以告诉我,我可以直接给你完整代码。

0 踩