栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C ++中的递归文件夹扫描

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C ++中的递归文件夹扫描

请参阅

manftw
以获取简单的“文件树遍历”。我也在
fnmatch
这个例子中使用过。

#include <ftw.h>#include <fnmatch.h>static const char *filters[] = {    "*.jpg", "*.jpeg", "*.gif", "*.png"};static int callback(const char *fpath, const struct stat *sb, int typeflag) {        if (typeflag == FTW_F) {        int i;                for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {  if (fnmatch(filters[i], fpath, FNM_CASEFOLD) == 0) {          printf("found image: %sn", fpath);     break; }        }    }        return 0;}int main() {    ftw(".", callback, 16);}

(甚至没有经过编译测试,但是您知道了。)

这比

DIRENT
自己处理s和递归遍历要简单得多。


为了更好地控制遍历,还提供了

fts
。在此示例中,点文件(名称以“。”开头的文件和目录)将被跳过,除非作为起点明确传递给程序。

#include <fts.h>#include <string.h>int main(int argc, char **argv) {    char *dot[] = {".", 0};    char **paths = argc > 1 ? argv + 1 : dot;    FTS *tree = fts_open(paths, FTS_NOCHDIR, 0);    if (!tree) {        perror("fts_open");        return 1;    }    FTSENT *node;    while ((node = fts_read(tree))) {        if (node->fts_level > 0 && node->fts_name[0] == '.') fts_set(tree, node, FTS_SKIP);        else if (node->fts_info & FTS_F) { printf("got file named %s at depth %d, "     "accessible via %s from the current directory "     "or via %s from the original starting directoryn",     node->fts_name, node->fts_level,     node->fts_accpath, node->fts_path);         }    }    if (errno) {        perror("fts_read");        return 1;    }    if (fts_close(tree)) {        perror("fts_close");        return 1;    }    return 0;}

同样,它既没有经过编译测试也没有运行测试,但我想我已经提到了。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/401022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号