参考别人的复制文件和复制文件夹,将他们合并成一个函数
- 功能: 文件拷贝
- 输入: fromDir源路径,toDir目标路径
- fromDir是文件或者是文件夹,toDir可以是文件夹也可以是文件
bool QWidget::copyDirectoryFiles(const QString &fromDir, const QString &toDir)
{
QFileInfo fromDirInfo(fromDir);
QFileInfo toDirInfo(toDir);
QDir sourceDir( fromDir );//源路径
QDir targetDir( toDir );//目标路径
if(fromDir == toDir)
return false;
if(!fromDirInfo.exists())//源文件不存在返回
return false;
if(toDirInfo.isFile())//不是目录
{
QString strname = toDirInfo.fileName();
QString dir = toDir;
dir.remove(strname);
targetDir.setPath(dir);
}
if(fromDirInfo.isFile())//复制文件
{
QString CopyName = targetDir.filePath(fromDirInfo.fileName());//将复制的文件名加在目标路径中
if(targetDir.exists(fromDirInfo.fileName()))//判断文件是否存在
{
targetDir.remove(fromDirInfo.fileName());
}
if(!QFile::copy(fromDir,CopyName))
{
return false;
}
}
else//复制文件夹
{
QString addpath = targetDir.absolutePath() + "/" + fromDirInfo.fileName();
targetDir.setPath(addpath);
if(!targetDir.exists())//如果目标目录不存在
{
if(!targetDir.mkdir(addpath))//进行创建
return false;
}
QFileInfoList fileInfoList = sourceDir.entryInfoList();
foreach(QFileInfo fileInfo,fileInfoList)
{
if ( fileInfo.fileName() == "." || fileInfo.fileName() == ".." )
continue;
if(fileInfo.isFile())
{
QString Name = targetDir.filePath(fileInfo.fileName());
if(targetDir.exists(fileInfo.fileName()))//判断文件是否存在
{
targetDir.remove(fileInfo.fileName());
}
if ( !QFile::copy(fileInfo.filePath(),Name))
{
return false;
}
}
else
{
if(!copyDirectoryFiles(fileInfo.filePath(),
targetDir.absolutePath()))
{
return false;
}
}
}
}
return true;
}
上述代码供参考,如有问题请告知!