版权声明:所有版权归作者她的吻让他,转载请标明出处. https://blog.csdn.net/qq_37059136/article/details/83578762
这里我将复制文件操作封装成一个接口,具体函数可以去查阅MSDN,相信你看过我这篇博客后,基本上关于文件的删除,拷贝,移动,改名都能顺利完成,因为他们用的是同一个函数:)
我这个接口不需要传具体的文件名字,只需传存放该文件的目录即可,当然你也可以通过该博客改写接口
先定义两个返回值类型
#define TRUE 0
#define FALSE 1
int CopyORBackUpFiles(string strFromPath,string strToPath)
{
//判断一个路径下文件夹是否存在
BOOL rec = PathFileExistsA(strFromPath.c_str());
if (0 ==rec)
{
return FALSE;
}
//查找文件是否存在
strFromPath+="\\";
string strFilesPath = strFromPath;
strFromPath+="*.*";
//替换文件路径
strToPath+="\\";
WIN32_FIND_DATA longFile;//定义文件信息结构体
HANDLE HFileHandle = FindFirstFileA(strFromPath.c_str(),(LPWIN32_FIND_DATAA)&longFile);
if (INVALID_HANDLE_VALUE == HFileHandle)
{
cout << GetLastError() << endl;
}
do
{
if(strcmp((char *)longFile.cFileName,".") == 0 || strcmp((char *)longFile.cFileName,"..") == 0)
{
continue;
}
//wcout << longFile_1.cFileName << endl;
//WIN32_FIND_DATA结构体中为Wchar,转为char
int len = wcslen(longFile.cFileName);
int ichar = WideCharToMultiByte(CP_ACP,0,longFile.cFileName,len,NULL,0,NULL,NULL);
char * pBuffer = new char[ichar + 1];
if (pBuffer)
{
ZeroMemory(pBuffer,ichar+1);
}
WideCharToMultiByte(CP_ACP,0,longFile.cFileName,len,pBuffer,ichar,NULL,NULL);
string strTargetFilename;
for (int i=0; i<ichar; i++)
{
strTargetFilename += pBuffer[i];
}
delete pBuffer;
pBuffer = NULL;
string ZIPFileName = strFilesPath;
ZIPFileName+=strTargetFilename;
//将解压文件路径转为TCHAR类型
int iUnicode = MultiByteToWideChar(CP_ACP, 0, ZIPFileName.c_str(), ZIPFileName.length(), NULL, 0);
WCHAR* pwUnicode = new WCHAR[iUnicode + 2];
if (pwUnicode)
{
ZeroMemory(pwUnicode, iUnicode + 2);
}
MultiByteToWideChar(CP_ACP, 0, ZIPFileName.c_str(), ZIPFileName.length(), pwUnicode, iUnicode);
pwUnicode[iUnicode] = '\0';
pwUnicode[iUnicode+1] = '\0';
int iRelativePath = MultiByteToWideChar(CP_ACP, 0, strToPath.c_str(), strToPath.length(), NULL, 0);
WCHAR* pwRelativePath = new WCHAR[iRelativePath + 2];
if (pwRelativePath)
{
ZeroMemory(pwRelativePath, iRelativePath + 2);
}
MultiByteToWideChar(CP_ACP, 0, strToPath.c_str(), strToPath.length(), pwRelativePath, iRelativePath);
pwRelativePath[iRelativePath] = '\0';
pwRelativePath[iRelativePath+1] = '\0';
//拷贝替换文件
SHFILEOPSTRUCT FileOp; //填写SHFILEOPSTRUCT结构体,通过SHFileOperation告诉windows该做什么
FileOp.hwnd = NULL;
FileOp.wFunc = FO_COPY;
FileOp.pFrom = (LPCWSTR)pwUnicode; //路径必须以双NULL结尾 ,源文件路径
FileOp.pTo = pwRelativePath; //路径必须以双NULL结尾 ,目的文件路径
FileOp.fFlags = FOF_NOCONFIRMATION | FOF_SILENT;
FileOp.hNameMappings = NULL;
FileOp.lpszProgressTitle = NULL;
//可以实现各种文件操作,例如文件的拷贝,移动,删除等
int nRet = SHFileOperation(&FileOp);
delete pwUnicode;
pwUnicode = NULL;
delete pwRelativePath;
pwRelativePath = NULL;
if(0 != nRet)
{
return FALSE;
}
} while (FindNextFile(HFileHandle,&longFile) != 0); //判断当前目录下有没有下一目录或文件
FindClose(HFileHandle); //关闭由FindFirstFile打开的搜索句柄
}
如果你编译出错,那么可能是某个函数没有添加头文件或引用库
可以添加这句试试
#include <Shlwapi.h>
#include <shlobj.h>
#pragma comment(lib, "shlwapi.lib")