![](/img/trans.png)
[英]Under linux / unix, how to discover if a directory is a link using c++?
[英]C++ Copy directory recursive under unix
下面是使用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);
}
請注意,使用標准庫的普通文件復制不會復制源文件的模式。 它還深層復制鏈接。 可能還會忽略一些我沒有提及的細節。 如果需要以不同方式處理,請使用POSIX特定功能。
我建議使用Boost,因為它可以移植到非POSIX系統,因為新的c ++標准文件系統API將基於它。
標准C ++沒有目錄的概念,只有文件。 對於你想做的事,你應該只使用Boost Filesystem 。 值得了解。 否則,您可以從C ++應用程序進行依賴於操作系統的調用。
另見這個SO線程:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.