VC中选择文件目录和打开文件对话框

时间:2022-12-17 12:17:58
在批量处理文件时常常用到,索性放BLOG里头。
void OnButtonOpen() {// TODO: Add your control notification handler code here/*CFileDialog cFlgDlg(TRUE,NULL,NULL,OFN_HIDEREADONLY |OFN_OVERWRITEPROMPT,NULL);cFlgDlg.m_ofn.lpstrInitialDir = _T("E:\\test\\");if(cFlgDlg.DoModal() == IDOK){SetDlgItemText(IDC_EDIT1,cFlgDlg.GetPathName());}*/BROWSEINFO bBowInfo;char szPathName[MAX_PATH];char szTitle[] = "选择文件目录";ZeroMemory(&bBowInfo, sizeof(BROWSEINFO));bBowInfo.hwndOwner = GetSafeHwnd();bBowInfo.pszDisplayName = szPathName;bBowInfo.lpszTitle = szTitle;bBowInfo.ulFlags = 0x0040 ; CString str;CString strDir; //选择的目录 LPITEMIDLIST lpList = SHBrowseForFolder(&bBowInfo);if(lpList == NULL){strDir= "";return;}SHGetPathFromIDList(lpList, str.GetBuffer(MAX_PATH * 2));str.ReleaseBuffer();if(str != "" && str.GetAt(str.GetLength() - 1) != '\\')str += "\\";strDir = str;SetDlgItemText(IDC_EDIT1,strDir);}

遍历文件子目录:

void FindALLFileFromPath(char * lpPath)
{
char szFind[MAX_PATH];
WIN32_FIND_DATA wFindData;
CString sMsg;

strcpy(szFind,lpPath);
strcat(szFind,"*.*");
HANDLE hFind = ::FindFirstFile(szFind,&wFindData);

if(hFind == INVALID_HANDLE_VALUE)
return;
while(TRUE)
{
if(wFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(wFindData.cFileName[0] != '.')
{
strcpy(szFind,lpPath);
strcat(szFind,wFindData.cFileName);
//递归查找
FindALLFileFromPath(szFind);
}
}
else
{
//找到文件并进行相应的转换
strcpy(szFind,lpPath);
strcat(szFind,wFindData.cFileName);
if(TranslateFileToAnsi(szFind))
{
sMsg.Format("文件%s转换成功!",wFindData.cFileName);
m_ListMsg.AddString(sMsg);
}//
else
{
sMsg.Format("文件%s转换失败!",wFindData.cFileName);
m_ListMsg.AddString(sMsg);
}

}
if(!FindNextFile(hFind,&wFindData))
{
break;
}
}

FindClose(hFind);
}