1. 程式人生 > >MFC下對檔案及資料夾的操作(複製、剪下、刪除、建立資料夾,寫檔案)

MFC下對檔案及資料夾的操作(複製、剪下、刪除、建立資料夾,寫檔案)

 1 void CFileOperationDlg::OnButtonCopy() 
 2 {
 3     // TODO: Add your control notification handler code here
 4     UpdateData(TRUE);
 5     CString m_strDestPath;
 6     m_strDestPath = "D:\\TestMyself\\FileOperation\\Debug";
 7     CString m_strSrcPath = "D:\\TestMyself\\FileOperation\\VISTA";
 8
CopyDirectory(m_strSrcPath,m_strDestPath); 9 } 10 11 BOOL CFileOperationDlg::CopyDirectory(CString strSrcPath,CString strDestPath) 12 { 13 CFileFind m_sFileFind; 14 if (strSrcPath.IsEmpty()) 15 { 16 OutputDebugString("原始檔名為空,無法進行拷貝!"); 17 return FALSE; 18 } 19 if
(!m_sFileFind.FindFile(strDestPath)) 20 { 21 CreateDirectory(strDestPath,NULL);//建立目標資料夾 22 } 23 CFileFind finder; 24 CString path; 25 path.Format("%s/*.*",strSrcPath); 26 //AfxMessageBox(path); 27 BOOL bWorking = finder.FindFile(path); 28 while (bWorking) 29 {
30 bWorking = finder.FindNextFile(); 31 //AfxMessageBox(finder.GetFileName()); 32 if (finder.IsDirectory() && !finder.IsDots())//是資料夾 而且 名稱不含 . 或 .. 33 { 34 CopyDirectory(finder.GetFilePath(),strDestPath+"/"+finder.GetFileName());//遞迴建立資料夾+"/"+finder.GetFileName() 35 } 36 else 37 {//是檔案,則直接複製 38 //AfxMessageBox("複製檔案"+finder.GetFilePath());//+finder.GetFileName() 39 CopyFile(finder.GetFilePath(),strDestPath+"/"+finder.GetFileName(),FALSE); 40 } 41 } 42 43 return TRUE; 44 } 45 46 CString CFileOperationDlg::GetFilePath() 47 { 48 CString m_FilePath; 49 50 GetModuleFileName(NULL,m_FilePath.GetBufferSetLength(MAX_PATH+1),MAX_PATH); 51 m_FilePath.ReleaseBuffer(); 52 53 int m_iPosIndex; 54 m_iPosIndex = m_FilePath.ReverseFind('\\'); 55 m_FilePath = m_FilePath.Left(m_iPosIndex+1); 56 57 return m_FilePath; 58 } 59 60 CString CFileOperationDlg::GetFileName() 61 { 62 CString sFileName; 63 64 sFileName = CTime::GetCurrentTime().Format("%Y-%m-%d") + TEXT(".log"); 65 66 return sFileName; 67 }