• 3.1.6 opendir、closedir、readdir


    包含头文件

    #include <dirent.h>
    #include <sys/types.h>

    opendir

    /***************************
     * 功能:打开目录文件
     * 参数:目录名
     * 返回值:成功返回指向目录文件的指针,失败返回NULL,并设置errno
     * ************************/
    DIR *opendir(const char pathname);

    closedir

    /***************************
     * 功能:关闭目录文件
     * 参数:指向目录文件的指针
     * 返回值:成功返回0,失败返回-1
     * ************************/
    int closedir(DIR *dirp);

    readdir

    /***************************
     * 功能:读取目录文件
     * 参数:指向目录文件的指针
     * 返回值:成功目录信息的结构体,失败返回NULL,并设置errno
     * ************************/
    struct dirent *readdir(DIR *dirp);
    
    struct dirent {
        ino_t          d_ino;       /* inode number */
        off_t          d_off;       /* offset to the next dirent */
        unsigned short d_reclen;    /* length of this record */
        unsigned char  d_type;      /* type of file; not supported
                                       by all file system types */
        char           d_name[256]; /* filename */
    };

    例子:

    /***********************
     *查看/etc目录所有文件
     **********************/
    #include <stdio.h>
    #include <stdlib.h>
    #include <dirent.h>
    #include <sys/types.h>
    
    #define PAT "/etc"
    
    
    int main()
    {
        //1.定义目录指针,结构体
        DIR *dp ;
        struct dirent *cur ;
        //2.打开目录文件
        dp = opendir(PAT);
        if(dp == NULL)
        {
            perror("opendir()");
            exit(1);
        }
        //3.读目录内容
        while((cur = readdir(dp)) != NULL)
        {
            puts(cur->d_name);
        }
        //4.关闭目录文件
        close(dp);
        exit(0);
    }
  • 相关阅读:
    钉钉outgoing机器人小项目开发
    js根据cookie判断,一天之内只弹出一次弹窗
    js倒计时功能
    jquery的$().each,$.each的区别
    VS代码提示自动高亮
    winform当前屏幕大小
    动态增删改控件
    datagridveiw样式
    sql 语句 提取中文的首字母
    按键监听及重写
  • 原文地址:https://www.cnblogs.com/muzihuan/p/5279620.html
Copyright © 2020-2023  润新知