拷贝文件、文件夹、创建文件夹、删除文件夹操作
来源:互联网 发布:金庸武侠知乎 编辑:程序博客网 时间:2024/05/22 03:18
Qt拷贝文件、文件夹、创建文件夹、删除文件夹操作
-
-
-
-
-
-
-
- bool MainWindow::copyFileToPath(QString srcFileName ,QString desFilePathName, bool coverFileIfExist,bool bDelSrcFile)
- {
- desFilePathName.replace("\\","/");
- if (srcFileName == desFilePathName){
- return true;
- }
- if (!QFile::exists(srcFileName)){
- return false;
- }
-
- makeDir(desFilePathName);
-
- QFileInfo srcFinfo(srcFileName);
- QFile srcFile(srcFileName);
-
- QString desFileName = desFilePathName+"/"+srcFinfo.fileName();
- QFile desFinfo(desFileName);
- if(desFinfo.exists()==true)
- {
- if(coverFileIfExist)
- {desFinfo.remove();}
- }
- QFile::copy(srcFileName,desFileName);
- if(bDelSrcFile)
- {
- srcFile.remove();
- }
-
- return true;
- }
-
-
-
-
- bool MainWindow::makeDir(QString dirName)
- {
- QStringList dirNameArray = dirName.split('/');
- int nameSize = dirNameArray.size();
- for(int i=1;i<nameSize+1;i++)
- {
- QString iBefAllDirStr="";
- for(int j=0;j<i;j++)
- {
- iBefAllDirStr += QString(dirNameArray.at(j)+'/');
- }
-
-
- QDir diri(iBefAllDirStr);
- if(diri.exists()==false)
- {diri.mkdir(iBefAllDirStr);}
- }
- return true;
- }
-
-
-
-
-
-
- bool MainWindow::copyDir(const QString &source, const QString &destination, bool override)
- {
- QDir directory(source);
- if (!directory.exists())
- {
- return false;
- }
-
-
- QString srcPath = QDir::toNativeSeparators(source);
- if (!srcPath.endsWith(QDir::separator()))
- srcPath += QDir::separator();
- QString dstPath = QDir::toNativeSeparators(destination);
- if (!dstPath.endsWith(QDir::separator()))
- dstPath += QDir::separator();
-
-
- bool error = false;
- QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
- for (QStringList::size_type i=0; i != fileNames.size(); ++i)
- {
- QString fileName = fileNames.at(i);
- QString srcFilePath = srcPath + fileName;
- QString dstFilePath = dstPath + fileName;
- QFileInfo fileInfo(srcFilePath);
- if (fileInfo.isFile() || fileInfo.isSymLink())
- {
- if (override)
- {
- QFile::setPermissions(dstFilePath, QFile::WriteOwner);
- }
- QFile::copy(srcFilePath, dstFilePath);
- }
- else if (fileInfo.isDir())
- {
- QDir dstDir(dstFilePath);
- dstDir.mkpath(dstFilePath);
- if (!copyDir(srcFilePath, dstFilePath, override))
- {
- error = true;
- }
- }
- }
-
-
- return !error;
- }
-
-
-
-
-
- bool MainWindow::DelDir(const QString &path)
- {
- if (path.isEmpty()){
- return false;
- }
- QDir dir(path);
- if(!dir.exists()){
- return true;
- }
- dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
- QFileInfoList fileList = dir.entryInfoList();
- foreach (QFileInfo file, fileList){
- if (file.isFile()){
- file.dir().remove(file.fileName());
- }else{
- DelDir(file.absoluteFilePath());
- }
- }
- return dir.rmpath(dir.absolutePath());
- }