温馨提示×

CentOS readdir读取隐藏文件方法

小樊
43
2025-11-29 22:31:24
栏目: 智能运维

在 CentOS 系统中,使用 readdir 函数读取目录时,默认情况下不会读取隐藏文件(以点开头的文件)。如果你想要读取隐藏文件,可以通过以下方法实现:

  1. 使用 opendirreaddir 函数遍历目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int main() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir("."); // 打开当前目录
    if (dir == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_name[0] == '.') { // 检查文件名是否以点开头
            printf("%s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}
  1. 使用 scandir 函数遍历目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int compare(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int main() {
    struct dirent **namelist;
    int n, i;

    n = scandir(".", &namelist, NULL, compare); // 扫描当前目录
    if (n < 0) {
        perror("scandir");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < n; i++) {
        if (namelist[i]->d_name[0] == '.') { // 检查文件名是否以点开头
            printf("%s\n", namelist[i]->d_name);
        }
        free(namelist[i]);
    }

    free(namelist);
    return 0;
}

这两个示例都会列出当前目录下的所有隐藏文件。你可以根据自己的需求修改代码以适应不同的目录。

0