1. 程式人生 > >MFC獲取資料夾下的所有檔名

MFC獲取資料夾下的所有檔名

1、獲取路徑:通過CFileDialog獲取資料夾的路徑,以及資料夾下面的一個檔案

  1. OnBnClickedBtnOpenfile()  
  2. {  
  3.     // TODO: Add your control notification handler code here    
  4.     CFileDialog dlg(TRUE);///TRUE為OPEN對話方塊,FALSE為SAVE AS對話方塊
  5.     CString csDirParth;  
  6.     if(dlg.DoModal()==IDOK)  
  7.         m_csFileName = dlg.GetPathName();  
  8.     else
  9.         m_csFileName.Empty();  
  10.     int iEndPos = 0;  
  11.     iEndPos = m_csFileName.ReverseFind('\\');  
  12.     csDirParth = m_csFileName.Left(iEndPos);  
  13.     m_FileList.clear();  
  14.     GetFileFromDir(csDirParth);  
  15. }  


2、下面的程式碼可以獲取路徑csDirPath下的txt檔案,並將所有的txt檔名儲存在vector<CString>型別的變數m_FileList中;

  1. GetFileFromDir(CString csDirPath)  
  2. {  
  3.     csDirPath+="\\*.txt";  
  4.     HANDLE file;  
  5.     WIN32_FIND_DATA fileData;  
  6.     char line[1024];  
  7.     char fn[1000];  
  8.     //mbstowcs(fn,csDirPath.GetBuffer(),999);
  9.     file = FindFirstFile(csDirPath.GetBuffer(), &fileData);  
  10.     m_FileList.push_back(fileData.cFileName);  
  11.     bool bState = 
    false;  
  12.     bState = FindNextFile(file, &fileData);  
  13.     while(bState){  
  14.         //wcstombs(line,(const char*)fileData.cFileName,259);
  15.         m_FileList.push_back(fileData.cFileName);  
  16.         bState = FindNextFile(file, &fileData);  
  17.     }  
  18. }