Qt 拷贝文件目录

时间:2022-03-15 14:42:36
 bool copyDir(const QString &source, const QString &destination, bool override)
{
QDir directory(source);
if (!directory.exists())
{
return false;
} QString srcPath = QDir::toNativeSeparators(source);
if (!srcPath.endsWith(QDir::separator()))
srcPath += QDir::separator();
QString dstPath = QDir::toNativeSeparators(destination);
if (!dstPath.endsWith(QDir::separator()))
dstPath += QDir::separator(); bool error = false;
QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
for (QStringList::size_type i=; i != fileNames.size(); ++i)
{
QString fileName = fileNames.at(i);
QString srcFilePath = srcPath + fileName;
QString dstFilePath = dstPath + fileName;
QFileInfo fileInfo(srcFilePath);
if (fileInfo.isFile() || fileInfo.isSymLink())
{
if (override)
{
QFile::setPermissions(dstFilePath, QFile::WriteOwner);
}
QFile::copy(srcFilePath, dstFilePath);
}
else if (fileInfo.isDir())
{
QDir dstDir(dstFilePath);
dstDir.mkpath(dstFilePath);
if (!copyDir(srcFilePath, dstFilePath, override))
{
error = true;
}
}
} return !error;
}

//另外一种

 // taken from utils/fileutils.cpp. We can not use utils here since that depends app_version.h.
static bool copyRecursively(const QString &srcFilePath,
const QString &tgtFilePath)
{
QFileInfo srcFileInfo(srcFilePath);
if (srcFileInfo.isDir()) {
QDir targetDir(tgtFilePath);
targetDir.cdUp();
if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
return false;
QDir sourceDir(srcFilePath);
QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
foreach (const QString &fileName, fileNames) {
const QString newSrcFilePath
= srcFilePath + QLatin1Char('/') + fileName;
const QString newTgtFilePath
= tgtFilePath + QLatin1Char('/') + fileName;
if (!copyRecursively(newSrcFilePath, newTgtFilePath))
return false;
}
} else {
if (!QFile::copy(srcFilePath, tgtFilePath))
return false;
}
return true;
}