随笔 - 51, 文章 - 1, 评论 - 41, 引用 - 0
数据加载中……

遍历Windows目录

不多说,在代码中。

 

/**
* @file directory_walker.h
* @brief 遍历目录功能分为遍历函数和动作类,动作类可根据不同用途重写,返回false表示中断遍历。
* @author lemene
*/

#ifndef DIRECTORY_WALKER_HPP
#define DIRECTORY_WALKER_HPP


#include <string>

class DirectoryWalker {
public:
    virtual bool EnterDirectory(const std::string& dirpath) { return true; }
    virtual bool LeaveDirectory(const std::string& dirpath) { return true; }
    virtual bool VisitFile(const std::string& filepath) { return true; }
};


bool WalkDirectory(const std::string& root, DirectoryWalker& walker);

#endif // DIRECTORY_WALKER_HPP

 

/**
* @file directory_walker.cpp
* @author lemene
*/
#include "directory_walker.hpp"

#include <windows.h>

bool WalkDirectory(const std::string& root, DirectoryWalker& walker)
{
    bool goon = true;
    std::string path = root + "\\*.*";
    WIN32_FIND_DATAA    wfd;
    HANDLE hFind = FindFirstFileA(path.c_str(), &wfd);

    if ((hFind != INVALID_HANDLE_VALUE))
    {
        do {
            if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if (strcmp(wfd.cFileName, ".") != 0 && strcmp(wfd.cFileName, "..") != 0)
                {
                    std::string dirpath = root + "\\" + wfd.cFileName;

                    goon = goon && walker.EnterDirectory(dirpath);
                    goon = goon && WalkDirectory(dirpath, walker);
                    goon = goon && walker.LeaveDirectory(dirpath);
                   
                }
            }
            else
            {
                goon = goon && walker.VisitFile(root + "\\" + wfd.cFileName);
            }

            if (!goon) break;

        } while (FindNextFileA(hFind, &wfd) != 0);

        FindClose(hFind);
    }

    return goon;
}

posted on 2014-06-24 21:34 lemene 阅读(318) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理