天天看點

Qt拷貝檔案、檔案夾(QFile::copy)

//拷貝檔案:
bool MyTest007::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
	toDir.replace("\\","/");
	if (sourceDir == toDir){
		return true;
	}
	if (!QFile::exists(sourceDir)){
		return false;
	}
	QDir *createfile     = new QDir;
	bool exist = createfile->exists(toDir);
	if (exist){
		if(coverFileIfExist){
			createfile->remove(toDir);
		}
	}//end if

	if(!QFile::copy(sourceDir, toDir))
	{
		return false;
	}
	return true;
}

//拷貝檔案夾:
bool MyTest007::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
{
	QDir sourceDir(fromDir);
	QDir targetDir(toDir);
	if(!targetDir.exists()){    /**< 如果目标目錄不存在,則進行建立 */
		if(!targetDir.mkdir(targetDir.absolutePath()))
			return false;
	}

	QFileInfoList fileInfoList = sourceDir.entryInfoList();
	foreach(QFileInfo fileInfo, fileInfoList){
		if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
			continue;

		if(fileInfo.isDir()){    /**< 當為目錄時,遞歸的進行copy */
			if(!copyDirectoryFiles(fileInfo.filePath(), 
				targetDir.filePath(fileInfo.fileName()),
				coverFileIfExist))
				return false;
		}
		else{            /**< 當允許覆寫操作時,将舊檔案進行删除操作 */
			if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
				targetDir.remove(fileInfo.fileName()); 
			}

			/// 進行檔案copy
			if(!QFile::copy(fileInfo.filePath(), 
				targetDir.filePath(fileInfo.fileName()))){
					return false;
			}
		}
	}
	return true;
}
           

繼續閱讀