Unix下的C ++复制目录递归 [英] C++ Copy directory recursive under unix

查看:114
本文介绍了Unix下的C ++复制目录递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c++ without additional libs上没有可用于将递归文件和文件夹复制到新位置的功能的任何示例.

There are no any examples of the functions ready for use on c++ without additional libs to Copy recursive files and folders to the new location.

system("cp -R -f dir");调用的某些替代方法.

Some alternative to system("cp -R -f dir"); call.

我仅在线程上找到此 C中的递归目录复制示例答案,但尚未准备好使用,我不确定此示例是否正确.

I'm only found this Recursive directory copying in C example on the thread answer, but its not ready for use and I'm not sure that this example is correct to start with.

也许有人在磁盘上有工作示例?

Maybe somebody have working example on the disk?

推荐答案

以下是使用POSIX和标准库函数进行递归复制的完整示例.

Here is a complete running example for recursive copying with POSIX and standard library functions.

#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特定功能.

Note that the trivial file copy using the standard library does not copy the mode of the source file. It also deep copies links. Might possibly also ignore some details that I didn't mention. Use POSIX specific functions if you need to handle those differently.

我建议改用Boost,因为它可以移植到非POSIX系统,并且新的c ++标准文件系统API将基于它.

I recommend using Boost instead because it's portable to non POSIX systems and because the new c++ standard filesystem API will be based on it.

这篇关于Unix下的C ++复制目录递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆