天天看點

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.     if(!QFile::copy(sourceDir, toDir))  
  19.     {  
  20.         return false;  
  21.     }  
  22.     return true;  
  23. }  
  24. //拷貝檔案夾:  
  25. bool MyTest007::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)  
  26. {  
  27.     QDir sourceDir(fromDir);  
  28.     QDir targetDir(toDir);  
  29.     if(!targetDir.exists()){      
  30.         if(!targetDir.mkdir(targetDir.absolutePath()))  
  31.             return false;  
  32.     }  
  33.     QFileInfoList fileInfoList = sourceDir.entryInfoList();  
  34.     foreach(QFileInfo fileInfo, fileInfoList){  
  35.         if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")  
  36.             continue;  
  37.         if(fileInfo.isDir()){      
  38.             if(!copyDirectoryFiles(fileInfo.filePath(),   
  39.                 targetDir.filePath(fileInfo.fileName()),  
  40.                 coverFileIfExist))  
  41.                 return false;  
  42.         }  
  43.         else{              
  44.             if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){  
  45.                 targetDir.remove(fileInfo.fileName());   
  46.             }  
  47.             /// 進行檔案copy  
  48.             if(!QFile::copy(fileInfo.filePath(),   
  49.                 targetDir.filePath(fileInfo.fileName()))){  
  50.                     return false;  
  51.             }  
  52.         }  
  53.     }  
  54.     return true;  
  55. }  

繼續閱讀