1.方法一(这个方法还没测试)
// taken from utils/fileutils.cpp. We can not use utils here since that depends app_version.h.
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;
}
2.方法2----递归拷贝子文件夹及文件
//
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=0; i != fileNames.size(); ++i)
for (QStringList::size_type i=0; 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;
}
递归删除所有
bool deleteDir(const QString &dirName)
{
QDir directory(dirName);
if (!directory.exists())
{
return true;
}
QString srcPath = QDir::toNativeSeparators(dirName);
if (!srcPath.endsWith(QDir::separator()))
srcPath += QDir::separator();
QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
bool error = false;
for (QStringList::size_type i=0; i != fileNames.size(); ++i)
{
QString filePath = srcPath + fileNames.at(i);
QFileInfo fileInfo(filePath);
if (fileInfo.isFile() || fileInfo.isSymLink())
{
QFile::setPermissions(filePath, QFile::WriteOwner);
if (!QFile::remove(filePath))
{
qDebug() << "remove file" << filePath << " faild!";
error = true;
}
}
else if (fileInfo.isDir())
{
if (!deleteDir(filePath))
{
error = true;
}
}
}
if (!directory.rmdir(QDir::toNativeSeparators(directory.path())))
{
qDebug() << "remove dir" << directory.path() << " faild!";
error = true;
}
return !error;
}
未完 ,待续