//清零一个蔟
//首先将win同步
//然后根据蔟号得到蔟的首扇区号
//清空win
//如果使能堆中申请内存
//则申请空间、清零空间、写入到磁盘对应扇区、释放空间
//如果没有使能堆,或申请空间失败
//则使用win空间,每次清零1个扇区,注意win空间为一个扇区大小
//整个蔟擦除则返回成功,否则返回失败。
static FRESULT dir_clear ( /* Returns FR_OK or FR_DISK_ERR */
FATFS *fs,//文件系统对象。/* Filesystem object */
DWORD clst//蔟号。该蔟用来存储根目录。/* Directory table to clear */
)
{
LBA_t sect;
UINT n, szb;
BYTE *ibuf;
if (sync_window(fs) != FR_OK) //将win同步
return FR_DISK_ERR; //同步失败,磁盘错误。/* Flush disk access window */
sect = clst2sect(fs, clst);//通过蔟号得到首扇区号。 /* Top of the cluster */
fs->winsect = sect;//配置扇区号。/* Set window to top of the cluster */
memset(fs->win, 0, sizeof fs->win);//清空win缓冲区。/* Clear window buffer */
#if FF_USE_LFN == 3//在堆上申请内存空间。/* Quick table clear by using multi-secter write */
/* Allocate a temporary buffer */
//如果每蔟扇区数*每扇区字节数大于等于MAX_MALLOC
//则szb使用MAX_MALLOC
//否则使用每蔟扇区数*每扇区字节数
//如果szb等于每扇区字节数,则没必要使用堆内存,直接使用win即可
//如果szb小于每扇区字节数,则申请内存不够一个扇区大小,直接使用功能win
//如果szb太大,申请失败了,则将szb减半再申请
for (szb = ((DWORD)fs->csize * SS(fs) >= MAX_MALLOC) ? MAX_MALLOC : fs->csize * SS(fs), ibuf = 0; \
szb > SS(fs) && (ibuf = ff_memalloc(szb)) == 0; \
szb /= 2) ;
if (szb > SS(fs)) {//buf申请成功。/* Buffer allocated? */
memset(ibuf, 0, szb);//清空buf
szb /= SS(fs); //计算申请空间是扇区大小的多少倍 /* Bytes -> Sectors */
//csize表示每蔟扇区数,n从0到csize - 1
//步进值为szb
//每次写的大小为szb个扇区
for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */
ff_memfree(ibuf);//释放空间
} else
#endif
{
ibuf = fs->win; //ibuf指向win缓冲区
szb = 1; /* Use window buffer (many single-sector writes may take a time) */
//csize:每蔟扇区数。
//sect为蔟中首扇区号。
//将ibuf中数据写入磁盘sect + n号扇区,每次写一个扇区
for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */
}
return (n == fs->csize) ? FR_OK : FR_DISK_ERR;//n等于每蔟扇区数,则说明整个蔟全部清零完了
}