linux

readdir如何与其他文件操作结合

小樊
38
2025-11-03 10:17:15
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常与其它文件操作函数结合使用,以实现更复杂的文件处理任务。以下是一些常见的结合使用方式:

1. 使用 opendirreaddir

首先,你需要使用 opendir 打开一个目录,然后使用 readdir 逐个读取目录中的条目。

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

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

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

2. 结合 stat 获取文件信息

你可以使用 stat 函数获取每个目录条目的详细信息,例如文件类型、大小、修改时间等。

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

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

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        char path[1024];
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISREG(file_stat.st_mode)) {
            printf("Regular file: %s\n", entry->d_name);
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("Directory: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

3. 结合 fopenfclose 读写文件

你可以根据 readdir 获取的文件名,使用 fopen 打开文件并进行读写操作。

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

int main() {
    DIR *dir;
    struct dirent *entry;
    FILE *file;
    char path[1024];

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strstr(entry->d_name, ".txt")) {
            snprintf(path, sizeof(path), "./%s", entry->d_name);
            file = fopen(path, "r");
            if (file == NULL) {
                perror("fopen");
                continue;
            }

            char buffer[1024];
            while (fgets(buffer, sizeof(buffer), file) != NULL) {
                printf("%s", buffer);
            }

            fclose(file);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

4. 结合 remove 删除文件

你可以根据某些条件删除目录中的文件。

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

int main() {
    DIR *dir;
    struct dirent *entry;
    char path[1024];

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strstr(entry->d_name, ".tmp")) {
            snprintf(path, sizeof(path), "./%s", entry->d_name);
            if (remove(path) == -1) {
                perror("remove");
            }
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

通过这些示例,你可以看到 readdir 如何与其他文件操作函数结合使用,以实现各种文件处理任务。根据具体需求,你可以灵活组合这些函数来完成更复杂的操作。

0
看了该问题的人还看了