Qt创建文件和文件夹的副本(QFile::copy)

[cpp]  view plain  copy
  1. //拷贝文件:  
  2. bool MyTest007::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)  
  3. {  
  4.     toDir.replace("\\","/");  
  5.     if (sourceDir == toDir){  
  6.         return true;  
  7.     }  
  8.     if (!QFile::exists(sourceDir)){  
  9.         return false;  
  10.     }  
  11.     QDir *createfile     = new QDir;  
  12.     bool exist = createfile->exists(toDir);  
  13.     if (exist){  
  14.         if(coverFileIfExist){  
  15.             createfile->remove(toDir);  
  16.         }  
  17.     }//end if  
  18.   
  19.     if(!QFile::copy(sourceDir, toDir))  
  20.     {  
  21.         return false;  
  22.     }  
  23.     return true;  
  24. }  
  25.   
  26. //拷贝文件夹:  
  27. bool MyTest007::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)  
  28. {  
  29.     QDir sourceDir(fromDir);  
  30.     QDir targetDir(toDir);  
  31.     if(!targetDir.exists()){    /**< 如果目标目录不存在,则进行创建 */  
  32.         if(!targetDir.mkdir(targetDir.absolutePath()))  
  33.             return false;  
  34.     }  
  35.   
  36.     QFileInfoList fileInfoList = sourceDir.entryInfoList();  
  37.     foreach(QFileInfo fileInfo, fileInfoList){  
  38.         if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")  
  39.             continue;  
  40.   
  41.         if(fileInfo.isDir()){    /**< 当为目录时,递归的进行copy */  
  42.             if(!copyDirectoryFiles(fileInfo.filePath(),   
  43.                 targetDir.filePath(fileInfo.fileName()),  
  44.                 coverFileIfExist))  
  45.                 return false;  
  46.         }  
  47.         else{            /**< 当允许覆盖操作时,将旧文件进行删除操作 */  
  48.             if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){  
  49.                 targetDir.remove(fileInfo.fileName());   
  50.             }  
  51.   
  52.             /// 进行文件copy  
  53.             if(!QFile::copy(fileInfo.filePath(),   
  54.                 targetDir.filePath(fileInfo.fileName()))){  
  55.                     return false;  
  56.             }  
  57.         }  
  58.     }  
  59.     return true;  
  60. }  

猜你喜欢

转载自blog.csdn.net/qq_33485434/article/details/80484339