Qt 拷贝文件目录
1 bool copyDir(const QString &source, const QString &destination, bool override) 2 { 3 QDir directory(source); 4 if (!directory.exists()) 5 { 6 return false; 7 } 8 9 10 QString srcPath = QDir::toNativeSeparators(source); 11 if (!srcPath.endsWith(QDir::separator())) 12 srcPath += QDir::separator(); 13 QString dstPath = QDir::toNativeSeparators(destination); 14 if (!dstPath.endsWith(QDir::separator())) 15 dstPath += QDir::separator(); 16 17 18 bool error = false; 19 QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden); 20 for (QStringList::size_type i=0; i != fileNames.size(); ++i) 21 { 22 QString fileName = fileNames.at(i); 23 QString srcFilePath = srcPath + fileName; 24 QString dstFilePath = dstPath + fileName; 25 QFileInfo fileInfo(srcFilePath); 26 if (fileInfo.isFile() || fileInfo.isSymLink()) 27 { 28 if (override) 29 { 30 QFile::setPermissions(dstFilePath, QFile::WriteOwner); 31 } 32 QFile::copy(srcFilePath, dstFilePath); 33 } 34 else if (fileInfo.isDir()) 35 { 36 QDir dstDir(dstFilePath); 37 dstDir.mkpath(dstFilePath); 38 if (!copyDir(srcFilePath, dstFilePath, override)) 39 { 40 error = true; 41 } 42 } 43 } 44 45 46 return !error; 47 }
//另外一种
1 // taken from utils/fileutils.cpp. We can not use utils here since that depends app_version.h. 2 static bool copyRecursively(const QString &srcFilePath, 3 const QString &tgtFilePath) 4 { 5 QFileInfo srcFileInfo(srcFilePath); 6 if (srcFileInfo.isDir()) { 7 QDir targetDir(tgtFilePath); 8 targetDir.cdUp(); 9 if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName())) 10 return false; 11 QDir sourceDir(srcFilePath); 12 QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System); 13 foreach (const QString &fileName, fileNames) { 14 const QString newSrcFilePath 15 = srcFilePath + QLatin1Char('/') + fileName; 16 const QString newTgtFilePath 17 = tgtFilePath + QLatin1Char('/') + fileName; 18 if (!copyRecursively(newSrcFilePath, newTgtFilePath)) 19 return false; 20 } 21 } else { 22 if (!QFile::copy(srcFilePath, tgtFilePath)) 23 return false; 24 } 25 return true; 26 } 27 28