温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中怎么遍历目录下的文件

发布时间:2021-08-12 16:49:50 来源:亿速云 阅读:145 作者:Leah 栏目:大数据

这篇文章给大家介绍C++中怎么遍历目录下的文件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

先上代码:

#include <iostream>

#include <dirent.h>

void print_dir(DIR *dir) {

    struct dirent *file;

    // 遍历文件夹下的内容

    while ((file = readdir(dir)) != NULL) {

        printf("文件位置=%ld ", telldir(dir));

        printf("子文件:%20s  ", file->d_name);

        printf("\n");

    }

}

int main(int argc, const char * argv[]) {

    const char *dirPATH = "/Users/ckend/Documents";

    DIR *dir = opendir(dirPATH);

    print_dir(dir);

    return 0;

}

需要用到的头文件:"dirent.h"

需要用到的结构及函数:"struct dirent"

"readdir()"

"opendir()"

"telldir()"

一个个地来讲解:

  1. dirent.h, 包含了许多关于目录操作的函数或结构的头文件。

  2. readdir(),来自于dirent.h,在程序内的语句:

    while ((file = readdir(dir)) != NULL) {}

    其作用是返回指向文件夹内的文件的dirent结构指针,它会逐一进行检查,直到没有更多的文件而返回NULL为止。

  3. opendir(),同样来自于dirent.h,其用于打开某个文件夹路径,并返回这个文件夹的DIR*指针。

  4. telldir(), 也是来自于dirent.h,它可以获得当前指针位置,并返回这个位置。

  5. struct dirent, 这个结构也是来自于dirent.其内容如下(摘自参考文献):


  6. struct dirent {ino_t          d_ino;       /* 在文件系统中的inode number */off_t          d_seekoff;   /* 与文件夹流的位置指针操作相关 */unsigned short d_reclen;    /* 本记录的数据长度 */unsigned char  d_type;      /* 当前遍历子项的文件类型:文件、文件夹、link、socket等 */char           d_name[256]; /* 当前遍历子项的文件名 */};

关于C++中怎么遍历目录下的文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI