FatFs检测并建立多层目录并更改文件名

时间:2022-07-23
本文章向大家介绍FatFs检测并建立多层目录并更改文件名,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

FatFs检测文件路径是否存在,不存在就建立多层目录,最后更改文件名

if(W_Dresult==FR_OK) 
{														
	wifi_dp_wav_file_status=0;
	start_downloading=0;

/*************************************遍历创建文件夹*************************************************************/
	u8 opendir_err = 0;   //错误提示
	char SonPath[10][50]; //最多10层,每层最多50字符
	char RootPath[200];   //最低已存在路径
	memset(SonPath, '', sizeof(SonPath)); //初始化
	memcpy(RootPath, DownFileName, sizeof(DownFileName));
	u8 num = 0;           // 剔除的次数
	do                      //遍历寻找文件夹
	{
		char *dot = strrchr(RootPath, '\');   //剔除一层
		memcpy(SonPath[num], dot, &RootPath[strlen(RootPath)] - dot);  //保存子目录
		for(int i=0;i<dot-RootPath;i++) RootPath[dot-RootPath+i] = '';
		
		W_Dresult = f_opendir(&W_Ddir, RootPath); //检测文件夹
		if(W_Dresult == FR_OK)
		{
			printf(">> 文件夹存在[%s]rn",RootPath);
			break;
		}
		else
		{
			printf(">> 文件夹打开错误 - %d [%s]rn",W_Dresult, RootPath);
			if(W_Dresult == FR_NO_PATH)
			{
				opendir_err = 1;
				num ++;
				continue;
			}
		}
	}
	while(1);
	if(opendir_err == 1)
	{
		//遍历创建文件夹
		opendir_err = 0;
		for(int i=0;i<num;i++)
		{
			memcpy(&RootPath[strlen(RootPath)], SonPath[num-i], strlen(SonPath[num-i]));
			W_Dresult = f_mkdir(RootPath);
			if(W_Dresult == FR_OK) { printf(">> 创建文件夹成功[%s]rn", RootPath); }
			else printf(">> 创建文件夹失败 - %d [%s]rn",W_Dresult, RootPath);
	}
	}
/****************************************************************************************/		

	W_Dresult = f_rename(recfilename,DownFileName);  //更改临时的文件名
	printf(">> 云端文件名:%srn",DownFileName);
	if(W_Dresult == FR_OK) printf(">> 更改文件名成功 - %srn",DownFileName);
	else printf(">> 更改文件名失败 - %drn",W_Dresult);
	if(W_Dresult == FR_EXIST)
	{
									printf(">> 文件已存在,删除旧文件rn");
		W_Dresult = f_unlink(DownFileName);  //删除旧文件
		if(W_Dresult == FR_OK) 
		{
			W_Dresult = f_rename(recfilename,DownFileName);  //更改临时的文件名
			if(W_Dresult == FR_OK) printf(">> 再次更改文件名成功 - %srn",DownFileName);
			else printf(">> 再次更改文件名失败 - %drn",W_Dresult);
		}
		else printf(">> 再次更改文件名失败 - %drn",W_Dresult);
	}
	
	return;
}