这是使用POSIX和标准库函数进行递归复制的完整运行示例。
#include <string>
#include <fstream>
#include <ftw.h>
#include <sys/stat.h>
const char* src_root ="foo/";
std::string dst_root ="foo2/";
constexpr int ftw_max_fd = 20; // I don't know appropriate value for this
extern "C" int copy_file(const char*, const struct stat, int);
int copy_file(const char* src_path, const struct stat* sb, int typeflag) {
std::string dst_path = dst_root + src_path;
switch(typeflag) {
case FTW_D:
mkdir(dst_path.c_str(), sb->st_mode);
break;
case FTW_F:
std::ifstream src(src_path, std::ios::binary);
std::ofstream dst(dst_path, std::ios::binary);
dst << src.rdbuf();
}
return 0;
}
int main() {
ftw(src_root, copy_file, ftw_max_fd);
}
请注意,使用标准库进行的琐碎文件复制不会复制源文件的模式。它还深复制链接。可能还会忽略我未提及的一些细节。如果需要以不同方式处理这些功能,请使用POSIX特定功能。
我建议改用Boost,因为它可以移植到非POSIX系统,并且新的c ++标准文件系统API将基于它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句