我这里有两个问题.第一个是大多数“foreach”风格循环的终止条件. STL样式迭代器通常在for的退出条件内使用operator!=,即
std::vector<int> test;for(std::vector<int>::iterator it = test.begin(); it != test.end(); it++) { //Do stuff}
我的问题是我不确定如何实现operator!=这样的目录枚举,因为我不知道枚举何时完成,直到我实际完成它.我现在有一个混合解决方案,它现在枚举整个目录,每个迭代器只是跟踪引用计数向量,但这似乎是一个可以做得更好的方法.
我遇到的第二个问题是FindXfile API返回了多个数据.出于这个原因,没有明显的方法来重载operator *作为迭代器语义的需要.当我重载该项时,是否返回文件名?尺寸?修改日期?我怎样才能传达这样一个迭代器必须在后来以一种思维方式引用的多个数据?我试过扯掉C#风格的MoveNext设计,但是我担心这里没有遵循标准的习语.
class SomeIterator {public: bool next(); //Advances the iterator and returns true if successful,false if the iterator is at the end. std::wstring filename() const; //other kinds of data....};
编辑:调用者看起来像:
SomeIterator x = ??; //Construct somehowwhile(x.next()) { //Do stuff}
谢谢!
Billy3
编辑2:我修复了一些错误并编写了一些测试.
执行:
#pragma once#include <queue>#include <string>#include <boost/noncopyable.hpp>#include <boost/make_shared.hpp>#include <boost/iterator/iterator_facade.hpp>#include <windows.h>#include <ShlwAPI.h>#pragma comment(lib,"shlwAPI.lib")#include "../Exception.hpp"namespace windowsAPI { namespace fileSystem {template <typename Filter_T = AllResults,typename Recurse_T = NonRecursiveEnumeration>class DirectoryIterator;//For unit testingstruct RealFindXfileFunctions{ static HANDLE FindFirst(LPCWSTR lpfilename,LPWIN32_FIND_DATAW lpFindfileData) { return FindFirstfile(lpfilename,lpFindfileData); }; static BOol FindNext(HANDLE hFindfile,LPWIN32_FIND_DATAW lpFindfileData) { return FindNextfile(hFindfile,lpFindfileData); }; static BOol Close(HANDLE hFindfile) { return FindClose(hFindfile); };};inline std::wstring::const_iterator GetLastSlash(std::wstring const&pathSpec) { return std::find(pathSpec.rbegin(),pathSpec.rend(),L'\').base();}class Win32FindData { WIN32_FIND_DATA internalData; std::wstring rootPath;public: Win32FindData(const std::wstring& root,const WIN32_FIND_DATA& data) : rootPath(root),internalData(data) {}; DWORD GetAttributes() const { return internalData.DWfileAttributes; }; bool IsDirectory() const { return (internalData.DWfileAttributes & file_ATTRIBUTE_DIRECTORY) != 0; }; bool Isfile() const { return !IsDirectory(); }; unsigned __int64 GetSize() const { ulARGE_INTEGER intValue; intValue.LowPart = internalData.nfileSizeLow; intValue.HighPart = internalData.nfileSizeHigh; return intValue.QuadPart; }; std::wstring GetFolderPath() const { return rootPath; }; std::wstring Getfilename() const { return internalData.cfilename; }; std::wstring GetFullfilename() const { return rootPath + L"\" + internalData.cfilename; }; std::wstring GetShortfilename() const { return internalData.cAlternatefilename; }; fileTIME GetCreationTime() const { return internalData.ftCreationTime; }; fileTIME GetLastAccesstime() const { return internalData.ftLastAccesstime; }; fileTIME GetLastWriteTime() const { return internalData.ftLastWriteTime; };};template <typename FindXfileFunctions_T>class BasicNonRecursiveEnumeration : public boost::noncopyable{ WIN32_FIND_DATAW currentData; HANDLE hFind; std::wstring currentDirectory; voID IncrementCurrentDirectory() { if (hFind == INVALID_HANDLE_VALUE) return; BOol success = FindXfileFunctions_T::FindNext(hFind,¤tData); if (success) return; DWORD error = GetLastError(); if (error == ERROR_NO_MORE_fileS) { FindXfileFunctions_T::Close(hFind); hFind = INVALID_HANDLE_VALUE; } else { windowsAPIException::Throw(error); } }; bool IsValIDDotDirectory() { return !ValID() && (!wcscmp(currentData.cfilename,L".") || !wcscmp(currentData.cfilename,L"..")); }; voID IncrementPastDotDirectorIEs() { while (IsValIDDotDirectory()) { IncrementCurrentDirectory(); } }; voID PerformFindFirstfile(std::wstring const&pathSpec) { hFind = FindXfileFunctions_T::FindFirst(pathSpec.c_str(),¤tData); if (ValID() && GetLastError() != ERROR_PATH_NOT_FOUND && GetLastError() != ERROR_file_NOT_FOUND) windowsAPIException::ThrowFromLastError(); };public: BasicNonRecursiveEnumeration() : hFind(INVALID_HANDLE_VALUE) {}; BasicNonRecursiveEnumeration(const std::wstring& pathSpec) : hFind(INVALID_HANDLE_VALUE) { std::wstring::const_iterator lastSlash = GetLastSlash(pathSpec); if (lastSlash != pathSpec.begin()) currentDirectory.assign(pathSpec.begin(),lastSlash-1); PerformFindFirstfile(pathSpec); IncrementPastDotDirectorIEs(); }; bool equal(const BasicNonRecursiveEnumeration<FindXfileFunctions_T>& other) const { if (this == &other) return true; return hFind == other.hFind; }; Win32FindData dereference() { return Win32FindData(currentDirectory,currentData); }; voID increment() { IncrementCurrentDirectory(); }; bool ValID() { return hFind == INVALID_HANDLE_VALUE; }; virtual ~BasicNonRecursiveEnumeration() { if (!ValID()) FindXfileFunctions_T::Close(hFind); };};typedef BasicNonRecursiveEnumeration<RealFindXfileFunctions> NonRecursiveEnumeration;template <typename FindXfileFunctions_T>class BasicRecursiveEnumeration : public boost::noncopyable{ std::wstring fileSpec; std::deque<std::deque<Win32FindData> > enumeratedData; voID EnumerateDirectory(const std::wstring& nextPathSpec) { std::deque<Win32FindData> newDeck; BasicNonRecursiveEnumeration<FindXfileFunctions_T> begin(nextPathSpec),end; for(; !begin.equal(end); begin.increment()) { newDeck.push_back(begin.dereference()); } if (!newDeck.empty()) { enumeratedData.push_back(std::deque<Win32FindData>()); //Swaptimization enumeratedData.back().swap(newDeck); } }; voID PerformIncrement() { if (enumeratedData.empty()) return; if (enumeratedData.back().front().IsDirectory()) { std::wstring nextSpec(enumeratedData.back().front().GetFullfilename()); nextSpec.append(L"\*"); enumeratedData.back().pop_front(); EnumerateDirectory(nextSpec); } else { enumeratedData.back().pop_front(); } while (ValID() && enumeratedData.back().empty()) enumeratedData.pop_back(); } bool CurrentpositionNoMatchfileSpec() const { return !enumeratedData.empty() && !PathMatchSpecW(enumeratedData.back().front().Getfilename().c_str(),fileSpec.c_str()); }public: BasicRecursiveEnumeration() {}; BasicRecursiveEnumeration(const std::wstring& pathSpec) { std::wstring::const_iterator lastSlash = GetLastSlash(pathSpec); if (lastSlash == pathSpec.begin()) { fileSpec = pathSpec; EnumerateDirectory(L"*"); } else { fileSpec.assign(lastSlash,pathSpec.end()); std::wstring firstquery(pathSpec.begin(),lastSlash); firstquery.push_back(L'*'); EnumerateDirectory(firstquery); while (CurrentpositionNoMatchfileSpec()) PerformIncrement(); } }; voID increment() { do { PerformIncrement(); } while (CurrentpositionNoMatchfileSpec()); }; bool equal(const BasicRecursiveEnumeration<FindXfileFunctions_T>& other) const { if (!ValID()) return !other.ValID(); if (!other.ValID()) return false; return this == &other; }; Win32FindData dereference() const { return enumeratedData.back().front(); }; bool ValID() const { return !enumeratedData.empty(); };};typedef BasicRecursiveEnumeration<RealFindXfileFunctions> RecursiveEnumeration;struct AllResults{ bool operator()(const Win32FindData&) { return true; };}; struct filesOnly{ bool operator()(const Win32FindData& arg) { return arg.Isfile(); };};template <typename Filter_T,typename Recurse_T>class DirectoryIterator : public boost::iterator_facade< DirectoryIterator<Filter_T,Recurse_T>,Win32FindData,std::input_iterator_tag,Win32FindData >{ frIEnd class boost::iterator_core_access; boost::shared_ptr<Recurse_T> impl; Filter_T filter; voID increment() { do { impl->increment(); } while (impl->ValID() && !filter(impl->dereference())); }; bool equal(const DirectoryIterator& other) const { return impl->equal(*other.impl); }; Win32FindData dereference() const { return impl->dereference(); };public: DirectoryIterator(Filter_T functor = Filter_T()) : impl(boost::make_shared<Recurse_T>()),filter(functor) { }; explicit DirectoryIterator(const std::wstring& pathSpec,Filter_T functor = Filter_T()) : impl(boost::make_shared<Recurse_T>(pathSpec)),filter(functor) { };};}}
测试:
#include <queue>#include "../WIDeCharacterOutput.hpp"#include <boost/test/unit_test.hpp>#include "../../windowsAPI++/fileSystem/Enumerator.hpp"using namespace windowsAPI::fileSystem;struct SimpleFakeFindXfileFunctions{ static std::deque<WIN32_FIND_DATAW> fakeData; static std::wstring insertedfilename; static HANDLE FindFirst(LPCWSTR lpfilename,LPWIN32_FIND_DATAW lpFindfileData) { insertedfilename.assign(lpfilename); if (fakeData.empty()) { SetLastError(ERROR_PATH_NOT_FOUND); return INVALID_HANDLE_VALUE; } *lpFindfileData = fakeData.front(); fakeData.pop_front(); return reinterpret_cast<HANDLE>(42); }; static BOol FindNext(HANDLE hFindfile,LPWIN32_FIND_DATAW lpFindfileData) { BOOST_CHECK_EQUAL(reinterpret_cast<HANDLE>(42),hFindfile); if (fakeData.empty()) { SetLastError(ERROR_NO_MORE_fileS); return 0; } *lpFindfileData = fakeData.front(); fakeData.pop_front(); return 1; }; static BOol Close(HANDLE hFindfile) { BOOST_CHECK_EQUAL(reinterpret_cast<HANDLE>(42),hFindfile); return 1; };};std::deque<WIN32_FIND_DATAW> SimpleFakeFindXfileFunctions::fakeData;std::wstring SimpleFakeFindXfileFunctions::insertedfilename;struct ErroneousFindXfileFunctionFirst{ static HANDLE FindFirst(LPCWSTR,LPWIN32_FIND_DATAW) { SetLastError(ERROR_ACCESS_DENIED); return INVALID_HANDLE_VALUE; }; static BOol FindNext(HANDLE hFindfile,LPWIN32_FIND_DATAW) { BOOST_CHECK_EQUAL(reinterpret_cast<HANDLE>(42),hFindfile); return 1; }; static BOol Close(HANDLE hFindfile) { BOOST_CHECK_EQUAL(reinterpret_cast<HANDLE>(42),hFindfile); return 1; };};struct ErroneousFindXfileFunctionNext{ static HANDLE FindFirst(LPCWSTR,LPWIN32_FIND_DATAW) { return reinterpret_cast<HANDLE>(42); }; static BOol FindNext(HANDLE hFindfile,hFindfile); SetLastError(ERROR_INVALID_ParaMETER); return 0; }; static BOol Close(HANDLE hFindfile) { BOOST_CHECK_EQUAL(reinterpret_cast<HANDLE>(42),hFindfile); return 1; };};struct DirectoryIteratorTestsFixture{ typedef SimpleFakeFindXfileFunctions fakeFunctor; DirectoryIteratorTestsFixture() { WIN32_FIND_DATAW test; wcscpy_s(test.cfilename,L"."); wcscpy_s(test.cAlternatefilename,L"."); test.DWfileAttributes = file_ATTRIBUTE_DIRECTORY; GetSystemTimeAsfileTime(&test.ftCreationTime); test.ftLastWriteTime = test.ftCreationTime; test.ftLastAccesstime = test.ftCreationTime; test.nfileSizeHigh = 0; test.nfileSizeLow = 0; fakeFunctor::fakeData.push_back(test); wcscpy_s(test.cfilename,L".."); wcscpy_s(test.cAlternatefilename,L".."); fakeFunctor::fakeData.push_back(test); wcscpy_s(test.cfilename,L"file.txt"); wcscpy_s(test.cAlternatefilename,L"file.TXT"); test.nfileSizeLow = 1024; test.DWfileAttributes = file_ATTRIBUTE_norMAL; fakeFunctor::fakeData.push_back(test); wcscpy_s(test.cfilename,L"System32"); wcscpy_s(test.cAlternatefilename,L"SYstem32"); test.nfileSizeLow = 0; test.DWfileAttributes = file_ATTRIBUTE_DIRECTORY; fakeFunctor::fakeData.push_back(test); }; ~DirectoryIteratorTestsFixture() { fakeFunctor::fakeData.clear(); };};BOOST_FIXTURE_TEST_SUITE( DirectoryIteratorTests,DirectoryIteratorTestsFixture )template<typename fakeFunctor>static voID NonRecursiveIteratorAssertions(){ typedef DirectoryIterator<AllResults,BasicNonRecursiveEnumeration<SimpleFakeFindXfileFunctions> > testType; testType begin(L"C:\windows\*"); testType end; BOOST_CHECK_EQUAL(fakeFunctor::insertedfilename,L"C:\windows\*"); BOOST_CHECK(begin->GetFolderPath() == L"C:\windows"); BOOST_CHECK(begin->Getfilename() == L"file.txt"); BOOST_CHECK(begin->GetFullfilename() == L"C:\windows\file.txt"); BOOST_CHECK(begin->GetShortfilename() == L"file.TXT"); BOOST_CHECK_EQUAL(begin->GetSize(),1024); BOOST_CHECK(begin->Isfile()); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin->Getfilename() == L"System32"); BOOST_CHECK(begin->GetFullfilename() == L"C:\windows\System32"); BOOST_CHECK(begin->GetShortfilename() == L"SYstem32"); BOOST_CHECK_EQUAL(begin->GetSize(),0); BOOST_CHECK(begin->IsDirectory()); begin++; BOOST_CHECK(begin == end);}BOOST_auto_TEST_CASE( BasicEnumeration ){ NonRecursiveIteratorAssertions<fakeFunctor>();}BOOST_auto_TEST_CASE( norootDirectorIEs ){ fakeFunctor::fakeData.pop_front(); fakeFunctor::fakeData.pop_front(); NonRecursiveIteratorAssertions<fakeFunctor>();}static voID EmptyIteratorAssertions() { typedef DirectoryIterator<AllResults,BasicNonRecursiveEnumeration<SimpleFakeFindXfileFunctions> > testType; testType begin(L"C:\windows\*"); testType end; BOOST_CHECK(begin == end);}BOOST_auto_TEST_CASE( Empty1 ){ fakeFunctor::fakeData.clear(); EmptyIteratorAssertions();}BOOST_auto_TEST_CASE( Empty2 ){ fakeFunctor::fakeData.erase(fakeFunctor::fakeData.begin() + 2,fakeFunctor::fakeData.end()); EmptyIteratorAssertions();}BOOST_auto_TEST_CASE( CorrectDestruction ){ typedef DirectoryIterator<AllResults,BasicNonRecursiveEnumeration<SimpleFakeFindXfileFunctions> > testType; testType begin(L"C:\windows\*"); testType end;}BOOST_auto_TEST_CASE( Exceptions ){ typedef DirectoryIterator<AllResults,BasicNonRecursiveEnumeration<ErroneousFindXfileFunctionFirst> > firstFailType; BOOST_CHECK_THROW(firstFailType(L"C:\windows\*"),windowsAPI::ErrorAccessDenIEdException); typedef DirectoryIterator<AllResults,BasicNonRecursiveEnumeration<ErroneousFindXfileFunctionNext> > nextFailType; nextFailType constructedOkay(L"C:\windows\*"); BOOST_CHECK_THROW(constructedOkay++,windowsAPI::ErrorInvalIDParameterException);}BOOST_auto_TEST_SUITE_END()struct RecursiveFakeFindXfileFunctions{ static std::deque<std::pair<std::deque<WIN32_FIND_DATA>,std::wstring> > fakeData; static std::size_t openHandles; static HANDLE FindFirst(LPCWSTR lpfilename,LPWIN32_FIND_DATAW lpFindfileData) { BOOST_REQUIRE(!fakeData.empty()); BOOST_REQUIRE_EQUAL(lpfilename,fakeData.front().second); openHandles++; BOOST_REQUIRE_EQUAL(openHandles,1); if (fakeData.front().first.empty()) { openHandles--; SetLastError(ERROR_PATH_NOT_FOUND); return INVALID_HANDLE_VALUE; } *lpFindfileData = fakeData.front().first.front(); fakeData.front().first.pop_front(); return reinterpret_cast<HANDLE>(42); }; static BOol FindNext(HANDLE hFindfile,hFindfile); if (fakeData.front().first.empty()) { SetLastError(ERROR_NO_MORE_fileS); return 0; } *lpFindfileData = fakeData.front().first.front(); fakeData.front().first.pop_front(); return 1; }; static BOol Close(HANDLE hFindfile) { BOOST_CHECK_EQUAL(reinterpret_cast<HANDLE>(42),hFindfile); openHandles--; BOOST_REQUIRE_EQUAL(openHandles,0); fakeData.pop_front(); return 1; };};std::deque<std::pair<std::deque<WIN32_FIND_DATA>,std::wstring> > RecursiveFakeFindXfileFunctions::fakeData;std::size_t RecursiveFakeFindXfileFunctions::openHandles;struct RecursiveDirectoryFixture{ RecursiveDirectoryFixture() { WIN32_FIND_DATAW tempData; ZeroMemory(&tempData,sizeof(tempData)); std::deque<WIN32_FIND_DATAW> dequeData; wcscpy_s(tempData.cfilename,L"."); wcscpy_s(tempData.cAlternatefilename,L"."); tempData.DWfileAttributes = file_ATTRIBUTE_DIRECTORY; GetSystemTimeAsfileTime(&tempData.ftCreationTime); tempData.ftLastWriteTime = tempData.ftCreationTime; tempData.ftLastAccesstime = tempData.ftCreationTime; dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L".."); wcscpy_s(tempData.cAlternatefilename,L".."); dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L"Mysubdirectory"); wcscpy_s(tempData.cAlternatefilename,L"MYSUBD~1"); dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L"Myfile.txt"); wcscpy_s(tempData.cAlternatefilename,L"MYfile.TXT"); tempData.nfileSizeLow = 500; tempData.DWfileAttributes = file_ATTRIBUTE_norMAL; dequeData.push_back(tempData); RecursiveFakeFindXfileFunctions::fakeData.push_back (std::make_pair(dequeData,L"C:\windows\*")); dequeData.clear(); wcscpy_s(tempData.cfilename,L"Myfile2.txt"); wcscpy_s(tempData.cAlternatefilename,L"NYfile2.TXT"); tempData.nfileSizeLow = 1024; tempData.DWfileAttributes = file_ATTRIBUTE_norMAL; dequeData.push_back(tempData); RecursiveFakeFindXfileFunctions::fakeData.push_back (std::make_pair(dequeData,L"C:\windows\Mysubdirectory\*")); }; ~RecursiveDirectoryFixture() { RecursiveFakeFindXfileFunctions::fakeData.clear(); };};BOOST_auto_TEST_SUITE( RecursiveDirectoryIteratorTests )BOOST_auto_TEST_CASE( BasicEnumerationTxt ){ RecursiveDirectoryFixture DataFixture; typedef DirectoryIterator<AllResults,BasicRecursiveEnumeration<RecursiveFakeFindXfileFunctions> > testType; testType begin(L"C:\windows\*.txt"); testType end; BOOST_CHECK(begin->Isfile()); BOOST_CHECK_EQUAL(begin->GetSize(),1024); BOOST_CHECK_EQUAL(begin->GetFolderPath(),L"C:\windows\Mysubdirectory"); BOOST_CHECK_EQUAL(begin->Getfilename(),L"Myfile2.txt"); BOOST_CHECK_EQUAL(begin->GetFullfilename(),L"C:\windows\Mysubdirectory\Myfile2.txt"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin->Isfile()); BOOST_CHECK_EQUAL(begin->GetSize(),500); BOOST_CHECK_EQUAL(begin->GetFolderPath(),L"C:\windows"); BOOST_CHECK_EQUAL(begin->Getfilename(),L"Myfile.txt"); BOOST_CHECK_EQUAL(begin->GetFullfilename(),L"C:\windows\Myfile.txt"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin == end);}BOOST_auto_TEST_CASE( BasicEnumerationAll ){ RecursiveDirectoryFixture DataFixture; typedef DirectoryIterator<AllResults,BasicRecursiveEnumeration<RecursiveFakeFindXfileFunctions> > testType; testType begin(L"C:\windows\*"); testType end; BOOST_CHECK(begin->IsDirectory()); BOOST_CHECK_EQUAL(begin->GetSize(),0); BOOST_CHECK_EQUAL(begin->GetFolderPath(),L"Mysubdirectory"); BOOST_CHECK_EQUAL(begin->GetFullfilename(),L"C:\windows\Mysubdirectory"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin->Isfile()); BOOST_CHECK_EQUAL(begin->GetSize(),L"C:\windows\Myfile.txt"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin == end);}BOOST_auto_TEST_CASE( RecursionorderMaintained ){ WIN32_FIND_DATAW tempData; ZeroMemory(&tempData,sizeof(tempData)); std::deque<WIN32_FIND_DATAW> dequeData; wcscpy_s(tempData.cfilename,L"."); wcscpy_s(tempData.cAlternatefilename,L"."); tempData.DWfileAttributes = file_ATTRIBUTE_DIRECTORY; GetSystemTimeAsfileTime(&tempData.ftCreationTime); tempData.ftLastWriteTime = tempData.ftCreationTime; tempData.ftLastAccesstime = tempData.ftCreationTime; dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L".."); wcscpy_s(tempData.cAlternatefilename,L".."); dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L"Mysubdirectory"); wcscpy_s(tempData.cAlternatefilename,L"MYSUBD~1"); dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L"Myfile.txt"); wcscpy_s(tempData.cAlternatefilename,L"MYfile.TXT"); tempData.nfileSizeLow = 500; tempData.DWfileAttributes = file_ATTRIBUTE_norMAL; dequeData.push_back(tempData); wcscpy_s(tempData.cfilename,L"Zach"); wcscpy_s(tempData.cAlternatefilename,L"ZACH"); tempData.DWfileAttributes = file_ATTRIBUTE_DIRECTORY; tempData.nfileSizeLow = 0; dequeData.push_back(tempData); RecursiveFakeFindXfileFunctions::fakeData.push_back (std::make_pair(dequeData,L"C:\windows\*")); dequeData.clear(); wcscpy_s(tempData.cfilename,L"Myfile2.txt"); wcscpy_s(tempData.cAlternatefilename,L"NYfile2.TXT"); tempData.nfileSizeLow = 1024; tempData.DWfileAttributes = file_ATTRIBUTE_norMAL; dequeData.push_back(tempData); RecursiveFakeFindXfileFunctions::fakeData.push_back (std::make_pair(dequeData,L"C:\windows\Mysubdirectory\*")); dequeData.clear(); wcscpy_s(tempData.cfilename,L"Zachfile.txt"); wcscpy_s(tempData.cAlternatefilename,L"ZACHfile.TXT"); tempData.nfileSizeLow = 1024; tempData.DWfileAttributes = file_ATTRIBUTE_norMAL; dequeData.push_back(tempData); RecursiveFakeFindXfileFunctions::fakeData.push_back (std::make_pair(dequeData,L"C:\windows\Zach\*")); typedef DirectoryIterator<AllResults,L"C:\windows\Myfile.txt"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin->IsDirectory()); BOOST_CHECK_EQUAL(begin->GetSize(),L"Zach"); BOOST_CHECK_EQUAL(begin->GetFullfilename(),L"C:\windows\Zach"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin->Isfile()); BOOST_CHECK_EQUAL(begin->GetSize(),L"C:\windows\Zach"); BOOST_CHECK_EQUAL(begin->Getfilename(),L"Zachfile.txt"); BOOST_CHECK_EQUAL(begin->GetFullfilename(),L"C:\windows\Zach\Zachfile.txt"); BOOST_CHECK(begin != end); begin++; BOOST_CHECK(begin == end);}BOOST_auto_TEST_CASE( Exceptions ){ typedef DirectoryIterator<AllResults,BasicRecursiveEnumeration<ErroneousFindXfileFunctionFirst> > firstFailType; BOOST_CHECK_THROW(firstFailType(L"C:\windows\*"),BasicRecursiveEnumeration<ErroneousFindXfileFunctionNext> > nextFailType; BOOST_CHECK_THROW(nextFailType(L"C:\windows\*"),windowsAPI::ErrorInvalIDParameterException);}BOOST_auto_TEST_SUITE_END()解决方法 有趣的是,我前段时间有同样的想法.这是我写的:
#define WIN32_LEAN_AND_MEAN#include <windows.h>#include <string>#include <iterator>#include <exception>#ifndef DIR_IteraTOR_H_INC#define DIR_IteraTOR_H_INCclass dir_iterator#if (!defined(_MSC_VER)) || (_MSC_VER > 1200) : public std::iterator<std::input_iterator_tag,std::string,int,std::string *,std::string &> #endif{ mutable HANDLE it; std::string mask; std::string path; WIN32_FIND_DATA data; bool done; DWORD require; DWORD prohibit;public: WIN32_FIND_DATA operator*() { return data; }dir_iterator(dir_iterator const &other) : it(other.it),mask(other.mask),path(other.path),data(other.data),done(other.done),require(other.require),prohibit(other.prohibit){ // Transfer the handle instead of just copying it. other.it=INVALID_HANDLE_VALUE;} dir_iterator(std::string const &s,DWORD must = 0,DWORD cant = file_ATTRIBUTE_DIRECTORY) : mask(s),require(must),prohibit(cant & ~must),done(false),it(INVALID_HANDLE_VALUE) // To fix BUG spotted by Billy ONeal. { int pos; if (std::string::npos != (pos=mask.find_last_of("\/"))) path = std::string(mask,pos+1); it = FindFirstfile(mask.c_str(),&data); if (it == INVALID_HANDLE_VALUE) throw std::invalID_argument("Directory Inaccessible"); while (!(((data.DWfileAttributes & require) == require) && ((data.DWfileAttributes & prohibit) == 0))) { if (done = (FindNextfile(it,&data)==0)) break; } } dir_iterator() : done(true) {} dir_iterator &operator++() { do { if (done = (FindNextfile(it,&data)==0)) break; } while (!(((data.DWfileAttributes & require) == require) && (data.DWfileAttributes & prohibit) == 0)); return *this; } bool operator!=(dir_iterator const &other) { return done != other.done; } bool operator==(dir_iterator const &other) { return done == other.done; } ~dir_iterator() { // The rest of the BUG fix -- only close handle if it's open. if (it!=INVALID_HANDLE_VALUE) FindClose(it); }};#endif
并快速演示它:
#include "dir_iterator.h"#include <iostream>#include <algorithm>namespace std { std::ostream &operator<<(std::ostream &os,WIN32_FIND_DATA const &d) { return os << d.cfilename; }}int main() { std::copy(dir_iterator("*"),dir_iterator(),std::ostream_iterator<WIN32_FIND_DATA>(std::cout,"\n")); std::cout << "\nDirectorIEs:\n"; std::copy(dir_iterator("*",file_ATTRIBUTE_DIRECTORY),"\n")); return 0;}总结
以上是内存溢出为你收集整理的我如何将FindXFile风格的API包装到C中的STL样式迭代器模式?全部内容,希望文章能够帮你解决我如何将FindXFile风格的API包装到C中的STL样式迭代器模式?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)