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

Stu*_*lli 13 c++ linux directory embedded

我想扫描目录树并列出每个目录中的所有文件和文件夹.我创建了一个从webcamera下载图像并在本地保存的程序.此程序根据图片下载的时间创建文件树.我现在想要扫描这些文件夹并将图像上传到网络服务器,但我不知道如何扫描目录以查找图像.如果有人可以发布一些示例代码,那将非常有帮助.

编辑:我在嵌入式Linux系统上运行它,不想使用boost

eph*_*ent 30

请参阅man ftw简单的"文件树步行".我也在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 it's a file */
    if (typeflag == FTW_F) {
        int i;
        /* for each filter, */
        for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {
            /* if the filename matches the filter, */
            if (fnmatch(filters[i], fpath, FNM_CASEFOLD) == 0) {
                /* do something */
                printf("found image: %s\n", fpath);
                break;
            }
        }
    }

    /* tell ftw to continue */
    return 0;
}

int main() {
    ftw(".", callback, 16);
}
Run Code Online (Sandbox Code Playgroud)

(甚至没有经过编译测试,但你明白了.)

这比处理DIRENTs和递归遍历要简单得多.


为了更好地控制遍历,还有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 directory\n",
                node->fts_name, node->fts_level,
                node->fts_accpath, node->fts_path);
            /* if fts_open is not given FTS_NOCHDIR,
             * fts may change the program's current working directory */
        }
    }
    if (errno) {
        perror("fts_read");
        return 1;
    }

    if (fts_close(tree)) {
        perror("fts_close");
        return 1;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

同样,它既没有经过编译测试也没有经过测试,但我想我会提到它.


Mar*_*ote 6

Boost.Filesystem允许你这样做.查看文档!

编辑:
如果您使用的是Linux并且不想使用Boost,则必须使用Linux本机C函数. 此页面显示了有关如何执行此操作的许多示例.