Unix下的C ++复制目录递归

编程入门 行业动态 更新时间:2024-10-28 16:30:17
本文介绍了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 ++复制目录递归

本文发布于:2023-10-08 23:50:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   目录   Unix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!