只需使用该代码,在参数中使用 old_dir、new_dir 调用“moveNodeAndSubNodes”。此代码非常安全,如果 som 不会删除 orig dir
#include <QDir>
#include <QDebug>
#include <QString>
#include <QDateTime>
#include <QFileInfoList>
#include <QFileInfo>
bool moveNodeAndSubNodes(QString from, QString to);
void moveDir(QString from, QString to);
QStringList findFiles(QString dir);
void moveDir(QString from, QString to)
{
qDebug() << "from=" << from << "to=" << to;
QDir source_dir(from);
if (source_dir.exists()) {
QDir dest_dir(to);
if (!dest_dir.exists()) {
qDebug() << "dest dir doesn't exist, create it" << to;
dest_dir.mkpath(".");
}
foreach (QFileInfo info, source_dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
QString old_path = info.absoluteFilePath();
QString new_path = QString("%1/%2").arg(to).arg(info.fileName());
if (info.isDir()) {
// recreate dir
qDebug() << "move dir" << old_path << "to" << new_path;
moveDir(old_path, new_path);
}
else {
// recreate file
qDebug() << "move file" << old_path << "to" << new_path;
QFile::rename(old_path, new_path);
}
}
}
else { qDebug() << "error : source dir doesn't exist :" << from; }
}
QStringList findFiles(QString dir)
{
QStringList ret;
QDir source_dir(dir);
if (source_dir.exists()) {
foreach (QFileInfo info, source_dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
if (info.isDir()) {
ret << findFiles(info.absoluteFilePath());
}
else {
ret << info.absoluteFilePath();
}
}
}
return ret;
}
bool moveNodeAndSubNodes(QString from, QString to)
{
bool ok = false;
moveDir(from, to);
QStringList files = findFiles(from);
qDebug() << "files not deleted =" << files;
if (files.isEmpty()) {
QDir rm_dir(from);
ok = rm_dir.removeRecursively();
qDebug() << "source dir removed =" << ok;
}
else {
qDebug() << "source dir not empty, not removed";
}
return ok;
}