记住上次遍历文件夹时的路径,递归遍历目录下的文件

时间:2021-07-29 12:27:15

1、浏览文件夹并记住上次选择目录

static TCHAR szDir[MAX_PATH] ;
int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lParam,LPARAM lpData)  

{
	LPITEMIDLIST tmp = (LPITEMIDLIST)lParam;
	switch (uMsg)
	{
	case BFFM_INITIALIZED:
		SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)lpData);
		break;
	case BFFM_SELCHANGED:
		TCHAR buffer[MAX_PATH];
		if (SHGetPathFromIDList((LPITEMIDLIST) tmp ,buffer))
		{
			SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)buffer);
		}
		break;
	default:
		break;
	}

	return 0;  
}

void OnBnClicked(UINT id)
{
	// TODO: 在此添加控件通知处理程序代码
	BROWSEINFO bi;
	memset(&bi, 0 , sizeof(bi));


	TCHAR Buffer[MAX_PATH] = {0};
	bi.hwndOwner = NULL;
	bi.pidlRoot =NULL;//初始化制定的root目录很不容易
	bi.pszDisplayName = Buffer;//此参数如为NULL则不能显示对话框
	bi.lpszTitle = _T("选择文件路径");


	bi.ulFlags = BIF_STATUSTEXT;//包括文件
	bi.lpfn = BrowseCallbackProc;
	bi.iImage=IDR_MAINFRAME;
	bi.lParam = (LPARAM)szDir;

	//初始化入口参数bi结束
	LPITEMIDLIST pIDList = SHBrowseForFolder(&bi);//调用显示选择对话框
	if(pIDList)
	{
		SHGetPathFromIDList(pIDList, Buffer);
		memcpy(szDir, Buffer, MAX_PATH);
		switch (id)
		{
		case IDC_INPUT:
			m_strInput = Buffer;
			break;
		case IDC_OUTPUT:
			m_strOutput = Buffer;
			break;
		default:
			break;
		}

		UpdateData(FALSE);
	}
	
	// free memory used     
	IMalloc * imalloc = 0;
	if ( SUCCEEDED(SHGetMalloc( &imalloc)))
	{
		imalloc->Free (pIDList);
		imalloc->Release();
	}
}

2、递归遍历目录下的文件

void RecursiveSearchDir(CString path)
{
	WIN32_FIND_DATA wData;
	memset(&wData, 0, sizeof(WIN32_FIND_DATA));
	CString strFind = path + _T("\\*.*");
	HANDLE hFind = FindFirstFile(strFind, &wData);
	if (INVALID_HANDLE_VALUE == hFind)
	{
		return;
	}

	do 
	{
		if (CString(wData.cFileName).CompareNoCase(_T(".")) && CString(wData.cFileName).CompareNoCase(_T("..")))
		{
			if (wData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				RecursiveSearchDir(path + _T("\\") + wData.cFileName);
			}
			else
			{
				CString fileName(path + _T("\\") + wData.cFileName);
				m_vecInput.push_back(fileName);
			}
		}
	} while ( FindNextFile(hFind, &wData));
}