C++实现将一个文件夹内容拷贝至另一个文件夹

时间:2023-01-25 16:05:22

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 }