简体   繁体   English

C ++复制目录在unix下递归

[英]C++ Copy directory recursive under unix

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. 没有任何准备在c++ without additional libs上使用的函数的示例, c++ without additional libs将复制文件和文件夹复制到新位置。

Some alternative to system("cp -R -f dir"); system("cp -R -f dir");一些替代品system("cp -R -f dir"); call. 呼叫。

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. 我只发现这个递归目录在线程答案的C示例中复制 ,但它还没有准备好使用,我不确定这个例子是否正确。

Maybe somebody have working example on the disk? 也许有人在磁盘上有工作示例?

Here is a complete running example for recursive copying with POSIX and standard library functions. 下面是使用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);
}

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. 如果需要以不同方式处理,请使用POSIX特定功能。

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. 我建议使用Boost,因为它可以移植到非POSIX系统,因为新的c ++标准文件系统API将基于它。

Standard C++ does not have the concept of a directory, only files. 标准C ++没有目录的概念,只有文件。 For what you wish to do you should probably just use Boost Filesystem . 对于你想做的事,你应该只使用Boost Filesystem It's worth getting to know. 值得了解。 Otherwise, you can make OS-dependent calls from your C++ app. 否则,您可以从C ++应用程序进行依赖于操作系统的调用。

See also this SO thread: 另见这个SO线程:

How do you iterate through every file/directory recursively in standard C++? 如何在标准C ++中递归遍历每个文件/目录?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM