操作系統提供的API通常不支持直接拷貝目錄樹。不過,可以通過遞歸的方法實現。下面,我們用boost的filesystem庫實現該功能。
-
- void CopyFiles(const boost::filesystem::path &src, const boost::filesystem::path &dst)
- {
- if (! boost::filesystem::exists(dst))
- {
- boost::filesystem::create_directories(dst);
- }
- for (boost::filesystem::directory_iterator it(src); it != boost::filesystem::directory_iterator(); ++it)
- {
- const boost::filesystem::path newSrc = src / it->filename();
- const boost::filesystem::path newDst = dst / it->filename();
- if (boost::filesystem::is_directory(newSrc))
- {
- CopyFiles(newSrc, newDst);
- }
- else if (boost::filesystem::is_regular_file(newSrc))
- {
- boost::filesystem::copy_file(newSrc, newDst, boost::filesystem::copy_option::overwrite_if_exists);
- }
- else
- {
- _ftprintf(stderr, "Error: unrecognized file - %s", newSrc.string().c_str());
- }
- }
- }
是不是很簡潔呢?該函數不僅可以拷貝目錄樹,還可以拷貝單個文件,而且輸入參數可以是相對路徑,您可以試試。
轉自:
http://blog.csdn.net/ganxinjiang/article/details/6088323