debian

Debian readdir函数使用指南

小樊
81
2025-02-17 19:07:16
栏目: 智能运维

readdir 函数是用于读取目录内容的 POSIX 函数。它在 <dirent.h> 头文件中定义。readdir 函数通常用于遍历一个目录中的所有条目(文件和子目录)。

函数原型

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

参数

返回值

struct dirent 结构

struct dirent 结构通常包含以下字段:

使用示例

以下是一个简单的示例,展示如何使用 readdir 函数遍历当前目录中的所有文件和子目录:

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

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

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

    // 遍历目录中的每个条目
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    // 关闭目录流
    if (closedir(dir) == -1) {
        perror("closedir");
        exit(EXIT_FAILURE);
    }

    return 0;
}

注意事项

0
看了该问题的人还看了