问题
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.
Some alternative to 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.
Maybe somebody have working example on the disk?
回答1:
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);
}
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.
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.
回答2:
Standard C++ does not have the concept of a directory, only files. For what you wish to do you should probably just use Boost Filesystem. It's worth getting to know. Otherwise, you can make OS-dependent calls from your C++ app.
See also this SO thread:
How do you iterate through every file/directory recursively in standard C++?
来源:https://stackoverflow.com/questions/36428121/c-copy-directory-recursive-under-unix