不多说,在代码中。
/**
* @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;
}