C++拷贝指定目录和子目录下的所有文件
时间: 2023-12-18 21:04:47 浏览: 109
和拷贝执行目录和子目录下的所有文件类似,只需要在递归函数中加入一个判断,只处理指定目录即可。具体步骤如下:
1. 使用<dirent.h>头文件中的opendir()函数打开指定目录,使用readdir()函数读取指定目录下的所有文件和子目录。
2. 对于每个子目录,使用递归函数来处理,即进入子目录,继续执行步骤1和2,直到找到所有文件。
3. 对于每个文件,使用C++的文件操作函数(如fstream)来读取并写入到目标目录。
下面是一个简单的示例代码:
```c++
#include <iostream>
#include <dirent.h>
#include <fstream>
void copyFiles(const std::string& sourceDir, const std::string& destDir)
{
DIR* dir = opendir(sourceDir.c_str());
dirent* p = nullptr;
while ((p = readdir(dir)) != nullptr) {
if (p->d_type == DT_DIR) {
// 处理子目录
if (strcmp(p->d_name, ".") == 0 || strcmp(p->d_name, "..") == 0) {
continue;
}
std::string subDir = sourceDir + "/" + p->d_name;
copyFiles(subDir, destDir);
}
else if (p->d_type == DT_REG) {
// 处理文件
std::string filePath = sourceDir + "/" + p->d_name;
std::ifstream inFile(filePath, std::ios::binary);
std::ofstream outFile(destDir + "/" + p->d_name, std::ios::binary);
outFile << inFile.rdbuf();
inFile.close();
outFile.close();
}
}
closedir(dir);
}
int main()
{
std::string sourceDir = "/path/to/source/dir";
std::string destDir = "/path/to/dest/dir";
copyFiles(sourceDir, destDir);
return 0;
}
```
这个程序将会拷贝指定目录和子目录下的所有文件到指定的目标目录中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)