复制单个文件
您可以使用QFile::copy。
QFile::copy(srcPath, dstPath);
注意:此功能不会覆盖文件,因此如果存在之前的文件,则必须删除它们:
if (QFile::exist(dstPath)) QFile::remove(dstPath);
如果您需要显示一个用户界面来获取源路径和目标路径,您可以使用QFileDialog 的方法来做到这一点。示例:
bool copyFiles() {
const QString srcPath = QFileDialog::getOpenFileName(this, "Source file", "",
"All files (*.*)");
if (srcPath.isNull()) return false; // QFileDialog dialogs return null if user canceled
const QString dstPath = QFileDialog::getSaveFileName(this, "Destination file", "",
"All files (*.*)"); // it asks the user for overwriting existing files
if (dstPath.isNull()) return false;
if (QFile::exist(dstPath))
if (!QFile::remove(dstPath)) return false; // couldn't delete file
// probably write-protected or insufficient privileges
return QFile::copy(srcPath, dstPath);
}
复制目录的全部内容
我将答案扩展到srcPath 是一个目录的情况。它必须手动和递归地完成。这是执行此操作的代码,为简单起见没有错误检查。您必须负责选择正确的方法(请查看QFileInfo::isFile 了解一些想法。
void recursiveCopy(const QString& srcPath, const QString& dstPath) {
QDir().mkpath(dstPath); // be sure path exists
const QDir srcDir(srcPath);
Q_FOREACH (const auto& dirName, srcDir.entryList(QStringList(), QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name)) {
recursiveCopy(srcPath + "/" + dirName, dstPath + "/" + dirName);
}
Q_FOREACH (const auto& fileName, srcDir.entryList(QStringList(), QDir::Files, QDir::Name)) {
QFile::copy(srcPath + "/" + fileName, dstPath + "/" + fileName);
}
}
如需查询目录,可使用QFileDialog::getExistingDirectory。
最后的评论
这两种方法都假定srcPath 存在。如果您使用QFileDialog 方法,它很可能存在(很可能是因为它不是原子操作,并且目录或文件可能会在对话框和复制操作之间被删除或重命名,但这是一个不同的问题) .