目前没有任何可以在c++不使用额外库
的情况下直接使用的函数示例,用于将递归文件和文件夹复制到新位置。
一些替代system("cp -R -f dir");
调用的方法。
我只找到了这个C语言递归目录拷贝的示例,但它还没有准备好使用,而且我也不确定这个示例是否正确。
也许有人在磁盘上有可用的示例?
#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);
}
Utils.h
中使用了您示例中的所有头文件,除了 ftw.h
。因此,只需要添加一个包含即可,这就像可以添加的一样简单),而且我不需要可移植性 :) - abrahabdst_root
必须已经存在于磁盘上。 - abrahab
boost::filesystem
在任何系统上都能运行,但事实并非如此。它只能在Windows和Posix系统上运行。 - SergeyA