QT操作文件夹(创建、复制、重命名、移除)

头文件

#include <QDir>
#include <QFileInfo>
#include <QFile>

创建文件夹

//************************************
// 方法名称:	CreateFolder
// 概要:		创建文件夹
// 返回值:		void
// 参数:		QString folderPath 文件夹路径
//************************************
void CreateFolder(QString folderPath)
{
	//创建文件夹
	QDir dir(folderPath);

	if (!dir.exists())
	{
		dir.mkdir(folderPath);
	}
}

复制文件夹


//************************************
// 方法名称:	copyFolder
// 概要:		复制文件夹
// 返回值:		bool
// 参数:		const QString & fromDir 原路径
// 参数:		const QString & toDir 新路径
// 参数:		bool coverFileIfExist 如果存在是否覆盖
//************************************
bool copyFolder(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 (!copyFolder(fileInfo.filePath(),
				targetDir.filePath(fileInfo.fileName()),
				coverFileIfExist))
				return false;
		}
		else
		{   //当允许覆盖操作时,将旧文件进行删除操作
			if (coverFileIfExist && targetDir.exists(fileInfo.fileName()))
			{
				targetDir.remove(fileInfo.fileName());
			}

			// 进行文件拷贝
			if (!QFile::copy(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName())))
			{
				return false;
			}
		}
	}
	return true;
}

重命名文件夹

//************************************
// 方法名称:	RenameFolder
// 概要:		重命名文件夹
// 返回值:		void
// 参数:		const QString oldPath 文件夹旧名称(全路径)
// 参数:		const QString newPath 文件夹新名称(全路径)
//************************************
void RenameFolder(const QString oldPath, const QString newPath)
{
	//重命名文件夹
	QDir dirOld(oldPath);
	dirOld.rename(oldPath, newPath);
}

移除文件夹

//************************************
// 方法名称:	RemoveFolder
// 概要:		移除文件夹
// 返回值:		void
// 参数:		QString dirPath 文件夹路径
//************************************
void RemoveFolder(const QString dirPath)
{
	//移除文件夹
	QDir dirItem(dirPath);
	dirItem.removeRecursively();
}

  • 11
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值