自己做個小小檔案搜查器

當不使用MFC時,若需要一個尋找目錄裡符合某個副檔名的函式,我們可以自己寫一個:
#include "stdafx.h"
#include <iostream>
#include <cassert>
#include <windows.h>
#include <atlstr.h>


class CFileFinder
{
public:
    ~CFileFinder()
    {
        if (m_hFinder != INVALID_HANDLE_VALUE)
        {
            ::FindClose(m_hFinder);
        }
    }

    bool IsFind() const 
    { 
        return (m_hFinder != INVALID_HANDLE_VALUE); 
    }

    CString GetFilePath() const
    {
        assert (m_hFinder != INVALID_HANDLE_VALUE );
        return CString(m_str + m_fd.cFileName);
    }

    CString GetFileTitle() const
    {
        assert (m_hFinder != INVALID_HANDLE_VALUE);
        CString str(m_fd.cFileName);
        int i = str.Find(_T('.'));
        return str.Left(i);
    }

    bool IsDirectory() const    
    {    
        return (m_fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 1;
    }

    bool Next()
    {
        assert (m_hFinder != INVALID_HANDLE_VALUE );
        if (::FindNextFile(m_hFinder , &m_fd) == 0)
        {
            if ( GetLastError() != ERROR_NO_MORE_FILES)
                m_hFinder = INVALID_HANDLE_VALUE;

            return false;
        }
        return true;
    }

protected:
    CFileFinder(const CString& strDir, const CString& strFilter) : m_str(strDir), m_hFinder(INVALID_HANDLE_VALUE)
    {
        CString strFindPath = strDir + strFilter;
        m_hFinder = ::FindFirstFile((const TCHAR*)strFindPath , &m_fd );
    }

    CString            m_str;
    HANDLE            m_hFinder;
    WIN32_FIND_DATA m_fd;    
};

要怎麼使用它呢,假設我們要搜尋某資料夾裡某個的tab檔案:
class TabFileFinder : public CFileFinder
{
public:
    TabFileFinder(const CString& strDir) : CFileFinder(strDir , _T("*.tab"))    {}
};

也可以直接打檔名,例如_T("XD.tab"),運用的時候就是:
    TabFileFinder finder(_T("C:\\Test\\"));
    while (finder.Next())
    {
        wprintf(_T("%s\n"), finder.GetFilePath());
    }
    system("pause");

不過,如果有其他工具可使用就更好啦。

0 意見:

張貼留言