Windows提供了非常好用的方法SHFileOperation,而且功能強大, 不光可以拷貝,還有移動、刪除等等操作。直接上代碼:
1 void CopyFolder(TCHAR* srcFolder, TCHAR* dstFolder) 2 { 3 SHFILEOPSTRUCT fop = {0}; 4 fop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR; 5 fop.wFunc = FO_COPY;//選擇執行類型,FO_COPY,FO_DELETE,FO_RENAME,FO_MOVE四種 6 7 fop.pFrom = srcFolder;//如:D:\\*.txt 8 fop.pTo = dstFolder;//D:\\test 9 10 SHFileOperation(&fop); 11 }
需要注意一點是,我在驗證的時候發現拷貝失效了,經過排查,發現傳入的參數有問題,因為我用的是char*,因此多了一層轉換,轉換出問題了(字符串顯示沒問題)。現將正確的TCHAR和char*互轉代碼貼出來
1 string TCHAR2char( const TCHAR* STR) 2 { 3 string strchar; 4 if (!*STR) 5 { 6 return strchar; 7 } 8 9 //返回字符串的長度 10 int size = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, FALSE); 11 12 //申請一個多字節的字符串變量 13 char* str = new char[size + 1]; 14 15 //將STR轉成str 16 WideCharToMultiByte(CP_ACP, 0, STR, -1, str, size, NULL, FALSE); 17 str[size] = '\0'; 18 strchar = str; 19 delete (str); 20 21 return strchar; 22 }
1 TCHAR* char2TCAHR(const char* str) 2 { 3 int size = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0); 4 TCHAR* retStr = new TCHAR[size + 1]; 5 MultiByteToWideChar(CP_ACP, 0, str, -1, retStr, size); 6 retStr[size] = '\0'; 7 return retStr; 8 }