⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 extractfilelistdlg.cpp

📁 通过vc语言从任意一个文件夹的读出文件名和路径操作的程序
💻 CPP
字号:
// ExtractFileListDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ExtractFileList.h"
#include "ExtractFileListDlg.h"
#include "ProcessDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define FIND_OVER_FLAG      0

#define BACKSLASH        _T("\\")
#define CRLF             _T("\r\n")
#define NULL_STRING      _T("")

extern DWORD volatile g_dwFileCount;

CString BrowsFolderPath(const CWnd* pWnd);
BOOL SaveFile(const char *pcFileName,  const char *pcData, int nSize);

/////////////////////////////////////////////////////////////////////////////
// CExtractFileListDlg dialog

CExtractFileListDlg::CExtractFileListDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CExtractFileListDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CExtractFileListDlg)
    m_bIsToFile = FALSE;
    m_bIsAppend = FALSE;
    m_bIsFullPath = FALSE;
    m_nPathOption = CExtractFileListDlg::PATH_RELATIVE;
    //}}AFX_DATA_INIT
    // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CExtractFileListDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CExtractFileListDlg)
    DDX_Check(pDX, IDC_TOFILE, m_bIsToFile);
    DDX_Check(pDX, IDC_APPEND, m_bIsAppend);
    DDX_Control(pDX, IDC_DRAGTIP, m_clsNotice);
	DDX_Control(pDX, IDC_FILELIST, m_editFileList);
    DDX_Control(pDX, IDC_FILECOUNT, m_clsFileCount);
    DDX_CBIndex(pDX, IDC_PATHOPTION, m_nPathOption);
    //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CExtractFileListDlg, CDialog)
    //{{AFX_MSG_MAP(CExtractFileListDlg)
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_MESSAGE(WM_SAVE_HWND, OnSaveHwnd)
    ON_BN_CLICKED(IDC_EXTRACT, OnExtract)
    ON_WM_DROPFILES()
	ON_WM_LBUTTONDOWN()
    ON_BN_CLICKED(IDC_BROWS, OnRootDir)
    ON_CBN_SELCHANGE(IDC_PATHOPTION, OnSelchangePathoption)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CExtractFileListDlg message handlers

BOOL CExtractFileListDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);            // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon
    
    // TODO: Add extra initialization here
    
    m_clsNotice.SetTextColor(RGB(0, 0, 255));
    m_clsFileCount.SetTextColor(RGB(255, 0, 0));

    return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CExtractFileListDlg::OnPaint() 
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting

        SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
        
        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialog::OnPaint();
    }
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CExtractFileListDlg::OnQueryDragIcon()
{
    return (HCURSOR) m_hIcon;
}

void CExtractFileListDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
	PostMessage(WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(point.x, point.y));
	CDialog::OnLButtonDown(nFlags, point);
}

void CExtractFileListDlg::OnExtract() 
{
    UpdateData();
    m_strFileList.Empty();
    UpdateData(FALSE);
    
    switch (m_nPathOption)
    {
    case (CExtractFileListDlg::PATH_RELATIVE) :
        {
            CString strTemp = NULL_STRING;
			CString strReplace = m_strRootPath + BACKSLASH;
            CString strRootDir = m_strRootPath.Left(m_strRootPath.ReverseFind(_TEXT('\\')));
            POSITION pos = m_strlstFile.GetHeadPosition();
            
            for ( pos; pos != 0; )
            {
                strTemp = m_strlstFile.GetNext(pos);
                strTemp.Replace(strReplace, NULL_STRING);
                m_strFileList += strTemp + CRLF;
            }
            m_strFileList.Delete(m_strFileList.GetLength() - 2, 2); // delete last redundant CRLF

            if (m_bIsAppend)
            {
                m_strFileList.Replace(CRLF, CRLF BACKSLASH);
                m_strFileList.Insert(0, BACKSLASH);
            }

            break;
        }
        
    case (CExtractFileListDlg::PATH_NAMEONLY) :
        {
            CString strTemp = NULL_STRING;

            POSITION pos = m_strlstFile.GetHeadPosition();
            
            for ( pos; pos != 0; )
            {
                strTemp = m_strlstFile.GetNext(pos);
                strTemp = strTemp.Right(strTemp.GetLength() - strTemp.ReverseFind(_TEXT('\\')) - 1);
                m_strFileList += strTemp + CRLF;
            }
            
            break;
        }
        
    case (CExtractFileListDlg::PATH_ABSOLUTE) :
        {
            POSITION pos = m_strlstFile.GetHeadPosition();
            for ( pos; pos != 0; )
            {
                m_strFileList += m_strlstFile.GetNext(pos) + CRLF;
            }

            break;
        }

    default:
        return;
    }

    if (!m_bIsToFile)
    {
        ((CEdit *)GetDlgItem(IDC_FILELIST))->SetWindowText(m_strFileList);
        return;
    }
    
    CString strDesktop; 
    ::SHGetSpecialFolderPath
        (
        this->m_hWnd,
        strDesktop.GetBuffer(MAX_PATH + 1),
        CSIDL_DESKTOP,
        false
        );
    strDesktop.ReleaseBuffer();

    CFileDialog saveDlg(FALSE, NULL, _T("filelist.txt"));
    saveDlg.m_ofn.lpstrFilter = _T("txt files (*.txt)\0 *.txt");
    saveDlg.m_ofn.lpstrTitle = _T("Choose your output file");
    saveDlg.m_ofn.lpstrInitialDir = strDesktop;
    CString strSavePath;

    if (saveDlg.DoModal() != IDOK)
    {
        return;
    }
    strSavePath = saveDlg.GetPathName();
    
    if (  SaveFile(strSavePath.GetBuffer(strSavePath.GetLength()),
          m_strFileList.GetBuffer(m_strFileList.GetLength()),
          m_strFileList.GetLength())
        )
    {
        ShowMessage(_T("FileList successfully saved!"));
    }
    else
    {
        ShowMessage(_T("FileList save failed!"));
    }

    strSavePath.ReleaseBuffer();
    m_strFileList.ReleaseBuffer();
}

void CExtractFileListDlg::OnDropFiles(HDROP hDropInfo)
{
    HANDLE hFile;
    WIN32_FIND_DATA wfdFile;
    CString strFilePath;
    UINT  iFileCount = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0); 

    InitState();

    for (UINT nIndex = 0 ; nIndex < iFileCount; ++nIndex)
    {
        UINT iLength = DragQueryFile(hDropInfo, nIndex, NULL, NULL) + 1;
        DragQueryFile(hDropInfo, nIndex, strFilePath.GetBuffer(iLength + 1), iLength);
        strFilePath.ReleaseBuffer();

        m_strRootPath = strFilePath;
        ((CEdit *)GetDlgItem(IDC_ROOTDIR))->SetWindowText(strFilePath);
        hFile = FindFirstFile(strFilePath, &wfdFile);

        if (hFile == INVALID_HANDLE_VALUE)
        {
            continue;
        }

        if (wfdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            m_dwFindOverFlag = FIND_OVER_FLAG;
            m_strFindPath = strFilePath;
            _beginthread(FindFile, 0, (void *)this);
            ProcessHandle();
        }
        else
        {
            m_strlstFile.AddTail(strFilePath);
        }
    }

    FindClose(hFile);
    DragFinish(hDropInfo);
}

void CExtractFileListDlg::OnRootDir() 
{
    CString strRootDir = BrowsFolderPath(this);
    if (strRootDir.IsEmpty())
    {
        // ShowErrMsg(_T("Invalid Root Path !"));
        return;
    }
    
    ((CEdit *)GetDlgItem(IDC_ROOTDIR))->SetWindowText(strRootDir);
    InitState();
	m_strRootPath = strRootDir;
    m_strFindPath = strRootDir;
    m_dwFindOverFlag = FIND_OVER_FLAG;
    _beginthread(FindFile, 0, (void *)this);
    ProcessHandle();
}

void CExtractFileListDlg::OnSelchangePathoption() 
{
    UpdateData();
    
    if (CExtractFileListDlg::PATH_RELATIVE == m_nPathOption)
    {
        GetDlgItem(IDC_APPEND)->EnableWindow();
    }
    else
    {
        GetDlgItem(IDC_APPEND)->EnableWindow(FALSE);
        m_bIsAppend = FALSE;
    }

    UpdateData(FALSE);
}

void CExtractFileListDlg::InitState()
{
    m_strFileList.Empty();
    m_strlstFile.RemoveAll();
    ((CEdit *)GetDlgItem(IDC_FILELIST))->SetWindowText(m_strFileList);
    ((CStatic *)GetDlgItem(IDC_FILECOUNT))->SetWindowText(_T(""));
    ((CStatic *)GetDlgItem(IDC_FILELABEL))->ShowWindow(SW_HIDE);
    g_dwFileCount = 0;
    Invalidate();
}

LRESULT CExtractFileListDlg::OnSaveHwnd(WPARAM wParam, LPARAM lParam)
{
    m_hWndProcess = (HWND)lParam;
    return 0;
}

void CExtractFileListDlg::ProcessHandle(void)
{
    CProcessDlg prcDlg;
    if (IDOK == prcDlg.DoModal())
    {
        if (m_strlstFile.GetCount() != 0)
        {
            ((CButton *)GetDlgItem(IDC_EXTRACT))->EnableWindow();
            CString strFileCount = NULL_STRING;
            strFileCount.Format(_T("%u"), m_strlstFile.GetCount());
            ((CStatic *)GetDlgItem(IDC_FILECOUNT))->SetWindowText(strFileCount);
            ((CStatic *)GetDlgItem(IDC_FILELABEL))->ShowWindow(SW_NORMAL);
            Invalidate();
        }
    }
    else
    {
        ((CEdit *)GetDlgItem(IDC_ROOTDIR))->SetWindowText(_T(""));
        ShowMessage(_T("You have canceled searching file!"));
        InitState();
    }
}

CString BrowsFolderPath(const CWnd *pWnd)
{
    CString strPath;
    strPath.Empty();

    if (NULL == pWnd)
    {
        return strPath;
    }

    BROWSEINFO brsInfo;
    ZeroMemory(&brsInfo, sizeof(brsInfo));
    brsInfo.hwndOwner = pWnd->GetSafeHwnd();
    brsInfo.lpszTitle = _T("Choose the root folder:");
    brsInfo.ulFlags = BIF_EDITBOX | BIF_RETURNONLYFSDIRS;
    LPITEMIDLIST lpDlist;
    lpDlist = SHBrowseForFolder(&brsInfo);

    if (lpDlist != NULL)
    {
        SHGetPathFromIDList(lpDlist, strPath.GetBuffer(MAX_PATH << 1));
        strPath.ReleaseBuffer();
    }

    return strPath;
}


void THREAD_FUNC FindFile(void *pHWnd)
{
    HANDLE hFile;
    BOOL bContinue = TRUE;
    WIN32_FIND_DATA wfdFile;
    CString strFileName, strFullPath, strInitialPath;
    CExtractFileListDlg *pMainDlg = (CExtractFileListDlg *)pHWnd;
    DWORD dwFindOverFlag = pMainDlg->m_dwFindOverFlag;

    strInitialPath = pMainDlg->m_strFindPath;
    ::SetCurrentDirectory(strInitialPath);
    hFile = FindFirstFile(_T("*.*"), &wfdFile);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        bContinue = FALSE;
    }

    while (bContinue)
    {
        strFileName = wfdFile.cFileName;
        strFullPath = strInitialPath + BACKSLASH + strFileName;

        if ((wfdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            && (wfdFile.cFileName[0] != _TEXT('.')))
        {
            ::SetCurrentDirectory(wfdFile.cFileName);
            pMainDlg->m_strFindPath = strFullPath;
            ++(pMainDlg->m_dwFindOverFlag);
            FindFile(pHWnd);
            SetCurrentDirectory(_T(".."));
        }
        else if (wfdFile.cFileName[0] != _TEXT('.'))
        {
			++g_dwFileCount;
            pMainDlg->m_strlstFile.AddTail(strFullPath);
        }

        bContinue = FindNextFile(hFile, &wfdFile);
    }

    FindClose(hFile);

    if (FIND_OVER_FLAG == dwFindOverFlag)
    {
		Sleep(10);  // cpu pipelining interrupt
        ::PostMessage(pMainDlg->m_hWndProcess, WM_FIND_OVER, 0, 0);
    }
}

BOOL SaveFile(const char *pcFileName,  const char *pcData, int nSize)
{
    FILE *fpSave = NULL;
    int nCount = 0;

    if ( (NULL == pcFileName) || (NULL == pcData) || (0 == nSize) )
    {
        return FALSE;
    }
    
    nCount = nSize;
    fpSave = fopen(pcFileName, "w+");

    if (NULL == fpSave)
    {
        return FALSE;
    }
    
    for (nCount; nCount > 0; --nCount)
    {
        if ( EOF == fputc(*(pcData++), fpSave) )
        {
            return FALSE;
        }
    }

    fclose(fpSave);
    return TRUE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -