mfc将文件拷贝到目标文件夹
时间: 2023-08-03 17:03:35 浏览: 91
你可以使用MFC的CFile类和CFileFind类来实现将文件拷贝到目标文件夹。以下是一个简单的示例代码:
```c++
CString strSourceFilePath = _T("source_file_path");
CString strDestFolderPath = _T("dest_folder_path");
// 打开源文件
CFile sourceFile;
if (sourceFile.Open(strSourceFilePath, CFile::modeRead) == FALSE)
{
// 处理打开文件失败的情况
return;
}
// 获取源文件名
CString strSourceFileName;
CFileFind sourceFileFinder;
if (sourceFileFinder.FindFile(strSourceFilePath))
{
sourceFileFinder.FindNextFile();
strSourceFileName = sourceFileFinder.GetFileName();
sourceFileFinder.Close();
}
// 拼接目标文件路径
CString strDestFilePath = strDestFolderPath + _T("\\") + strSourceFileName;
// 创建目标文件夹
CFileFind destFolderFinder;
if (destFolderFinder.FindFile(strDestFolderPath) == FALSE)
{
if (CreateDirectory(strDestFolderPath, NULL) == FALSE)
{
// 处理创建文件夹失败的情况
sourceFile.Close();
return;
}
}
// 创建目标文件
CFile destFile;
if (destFile.Open(strDestFilePath, CFile::modeCreate | CFile::modeWrite) == FALSE)
{
// 处理创建文件失败的情况
sourceFile.Close();
return;
}
// 读取并写入数据
BYTE buffer[1024];
UINT nBytesRead;
while ((nBytesRead = sourceFile.Read(buffer, 1024)) > 0)
{
destFile.Write(buffer, nBytesRead);
}
// 关闭文件
sourceFile.Close();
destFile.Close();
```
在示例代码中,source_file_path表示源文件的路径,dest_folder_path表示目标文件夹的路径。示例代码中使用了CFileFind类来获取源文件名和检查目标文件夹是否存在。你也可以使用其他方法来获取源文件名和检查目标文件夹是否存在。