Click here to Skip to main content
15,896,269 members
Articles / Desktop Programming / MFC

Win32 File Name Iteration Boost Way

Rate me:
Please Sign up or sign in to vote.
4.71/5 (10 votes)
3 Nov 2005CPOL2 min read 57.1K   397   17  
A Port of ::FindFirstFile to Boost.Range and Boost.Foreach
#pragma once

#include <cassert>
#include <boost/iterator/iterator_facade.hpp>

namespace find_file {

struct find_file_iterator :
	boost::iterator_facade<
		find_file_iterator,
		WIN32_FIND_DATA,
		boost::single_pass_traversal_tag
	>
{
	// See: sgi.STL::istream_iterator

	find_file_iterator() : // the end iterator
		m_found(false)
	{ }

	find_file_iterator(HANDLE hFind, WIN32_FIND_DATA& data) :
		m_hFind(hFind), m_pdata(&data), m_found(hFind != INVALID_HANDLE_VALUE)
	{ }

private:
	HANDLE m_hFind;
	WIN32_FIND_DATA *m_pdata;
	bool m_found;

	void find_next_file()
	{
		m_found = (::FindNextFile(m_hFind, m_pdata) != FALSE);

		if (!m_found)
			assert(::GetLastError() == ERROR_NO_MORE_FILES);
	}

	bool equal_aux(find_file_iterator const& other) const
	{
		return m_hFind == other.m_hFind && m_pdata == other.m_pdata;
	}

// iterator_facade implementation
	friend class boost::iterator_core_access;

	void increment()
	{
		assert(m_found && _T("find_file::find_file_iterator - iterator is invalid."));

		find_next_file();
	}

	bool equal(find_file_iterator const& other) const
	{
		return (m_found == other.m_found) && (!m_found || equal_aux(other));
	}

	WIN32_FIND_DATA& dereference() const
	{
		assert(m_found && _T("find_file::find_file_iterator - iterator gets an access violation"));

		return *m_pdata;
	}
};

} // namespace find_file

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Japan Japan
I am worried about my poor English...

Comments and Discussions