复制目录内容

我想将内容目录(tmp1)复制到另一个目录(tmp2)。 tmp1可能包含文件和其他目录。 我想使用C / C ++复制tmp1的内容(包括模式)。 如果tmp1包含一个目录树,我想以递归方式复制它们。

什么是最简单的解决方案?

我找到了一个解决方案来打开目录并读取每个条目并使用cp命令复制它。 更简单的解决方案?

我建议使用std::filesystem (从C ++ 17开始合并到ISO C ++!)

无耻地从http://en.cppreference.com/w/cpp/filesystem/copy复制:

std::filesystem::copy("/dir1", "/dir3", std::filesystem::copy_options::recursive);

阅读更多相关信息:

https://gcc.gnu.org/onlinedocs/gcc-6.1.0/libstdc++/api/a01832.html

experimental :: filesystem链接器错误

最近我有同样的需求,所以我开发了下一块代码以解决问题。 我希望它对同样情况下的另一个人有所帮助。

 #include  #include  #include  #include  #include  using namespace std; bool is_dir(const char* path); void copyFile_(string inDir, string outDir); void copyDir_(const char *inputDir, string outDir); int main() { string srcDir = "C:\\testDirectory"; string destDir = "C:\\destDir"; copyDir_(srcDir.c_str(), destDir); return 0; } void copyDir_(const char *inputDir, string outDir) { DIR *pDIR; struct dirent *entry; string tmpStr, tmpStrPath, outStrPath, inputDir_str = inputDir; if (is_dir(inputDir) == false) { cout << "This is not a folder " << endl; return; } if( pDIR = opendir(inputDir_str.c_str()) ) { while(entry = readdir(pDIR)) // get folders and files names { tmpStr = entry->d_name; if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 ) { tmpStrPath = inputDir_str; tmpStrPath.append( "\\" ); tmpStrPath.append( tmpStr ); cout << entry->d_name; if (is_dir(tmpStrPath.c_str())) { cout << "--> It's a folder" << "\n"; // Create Folder on the destination path outStrPath = outDir; outStrPath.append( "\\" ); outStrPath.append( tmpStr ); mkdir(outStrPath.c_str()); copyDir_(tmpStrPath.c_str(), outStrPath); } else { cout << "--> It's a file" << "\n"; // copy file on the destination path outStrPath = outDir; outStrPath.append( "\\" ); outStrPath.append( tmpStr ); copyFile_(tmpStrPath.c_str(), outStrPath.c_str()); } } } closedir(pDIR); } } bool is_dir(const char* path) { struct stat buf; stat(path, &buf); return S_ISDIR(buf.st_mode); } void copyFile_(string inDir, string outDir) { CopyFile(inDir.c_str(), outDir.c_str(), 1); DWORD Error = GetLastError(); }