C++ – Dirwalk Sınıfı

Dirwalk Sınıfı: Bir dizindeki dosyaları listeler.

#include <windows.h>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstring>
#include <io.h>

using namespace std;

class DirWalk {
private:
	friend class DirWalkIter;

	class DirWalkIter : public iterator<input_iterator_tag, _finddata_t> {
	public:
		DirWalkIter()
		{
			m_fd = -1;
		}

		DirWalkIter(long fd, const _finddata_t ¤t) : m_fd(fd), m_current(current)
		{}
		~DirWalkIter()
		{
			if (m_fd != -1)
				::_findclose(m_fd);
		}
		bool operator ==(const DirWalkIter &iter) const
		{
			return memcmp(&m_current, &iter.m_current, sizeof(m_current)) == 0;
		}
		bool operator !=(const DirWalkIter &iter) const
		{
			return memcmp(&m_current, &iter.m_current, sizeof(m_current)) != 0;
		}
		_finddata_t operator *()
		{
			return m_current;
		}
		DirWalkIter &operator ++()
		{
			if (_findnext(m_fd, &m_current) == -1)
				m_current = ms_null;

			return *this;
		}

		DirWalkIter operator ++(int)
		{
			DirWalkIter temp(*this);

			if (::_findnext(m_fd, &m_current) == -1)
				m_current = ms_null;

			return temp;
		}
		_finddata_t *operator ->()
		{
			return &m_current;
		}

	private:
		long m_fd;
		_finddata_t m_current;
		static _finddata_t ms_null;
	};
public:
	DirWalk(const char *pszPath) : m_path(pszPath)
	{}
	typedef DirWalkIter iterator;

	iterator begin()
	{
		long fdh;
		_finddata_t fd;

		fdh = ::_findfirst(m_path.c_str(), &fd);
		return DirWalkIter(fdh, fd);
	}

	iterator end()
	{
		_finddata_t fd = {0};

		return iterator(-1, fd);
	}
private:
	string m_path;
};

_finddata_t DirWalk::DirWalkIter::ms_null = {0};

void Disp(const _finddata_t &fd)
{
	cout << fd.name << "n";
}

int main(void)
{
	DirWalk dir("c:\*.*");

	for_each(dir.begin(),  dir.end(), Disp);

	return 0;
}

Bir cevap yazın

E-posta hesabınız yayımlanmayacak.