CopyFile只能复制一个文件,要想复制整个文件夹的所有文件,需要遍历文件夹里面的文件。
MyFile.h
#pragma once
#include <string>
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <io.h>
#include <string>
#include <Shlwapi.h>
using namespace std;
class CMyFile
{
public:
explicit CMyFile(void);
~CMyFile(void);
static void MyCopyFile(string sourceFilePath,string destFilePath);
};
MyFile.cpp
#include "StdAfx.h"
#include "MyFile.h"
LPCWSTR StringToLPCWSTR(string orig);
void CopyFileRealize(string filePath,string destPath);
void FindAllFile(string sourcePath,string destPath);
CMyFile::CMyFile(void)
{
/* void MyCopyFile(string sourceFilePath,string destFilePath);
FindAllFile(sourceFilePath,destFilePath);*/
}
CMyFile::~CMyFile(void)
{
}
void CMyFile::MyCopyFile(string sourceFilePath,string destFilePath)
{
FindAllFile(sourceFilePath,destFilePath);
}
void CopyFileRealize(string filePath,string destPath)
{
string newFilePath=destPath+filePath.substr(2,filePath.length());
int lastIndex=newFilePath.find_last_of("\\");
string destDir=newFilePath.substr(0,lastIndex);
string destFileName=newFilePath.substr(lastIndex);
LPCWSTR wFilePath=StringToLPCWSTR(filePath);
LPCWSTR wDestDir=StringToLPCWSTR(destDir);
LPCWSTR wDestFilePath=StringToLPCWSTR(destDir+destFileName);
if(_access(destDir.c_str(),0)==-1)
{
CreateDirectory(wDestDir,NULL);
}
CopyFile(wFilePath,wDestFilePath,FALSE);
}
void FindAllFile(string sourcePath,string destPath)
{
struct _finddata_t FileInfo;
string strFind=sourcePath+"\\*";
long Handle=_findfirst(strFind.c_str(),&FileInfo);
if(Handle==-1L)
{
cerr << "can not match the folder path" << endl;
exit(-1);
}
do{
//判断是否有子目录
if((FileInfo.attrib&_A_SUBDIR)==_A_SUBDIR)
{
if((strcmp(FileInfo.name,".")!=0)&&(strcmp(FileInfo.name,"..")!=0))
{
string newPath=sourcePath+"\\"+FileInfo.name;
FindAllFile(newPath,destPath);
}
}
else
{
string filePath=sourcePath+"\\"+FileInfo.name;
CopyFileRealize(filePath,destPath);
}
}while(_findnext(Handle,&FileInfo)==0);
_findclose(Handle);
// fout.close();
}
LPCWSTR StringToLPCWSTR(string orig)
{
size_t origsize = orig.length() + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length()-1));
mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
return wcstring;
}
使用
CMyFile::MyCopyFile("E:\\Test1","E:\\T2");