1 /*-----------------------------------------------------------------------*/ 2 /* Get Number of Free Clusters */ 3 /*-----------------------------------------------------------------------*/ 4 5 FRESULT f_getfree ( 6 const TCHAR *path, /* Pointer to the logical drive number (root dir) */ 7 DWORD *nclst, /* Pointer to the variable to return number of free clusters */ 8 FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */ 9 ) 10 { 11 FRESULT res; 12 DWORD n, clst, sect, stat; 13 UINT i; 14 BYTE fat, *p; 15 16 17 /* Get drive number */ 18 res = chk_mounted(&path, fatfs, 0); 19 if (res == FR_OK) { 20 /* If free_clust is valid, return it without full cluster scan */ 21 if ((*fatfs)->free_clust <= (*fatfs)->n_fatent - 2) { 22 *nclst = (*fatfs)->free_clust; 23 } else { 24 /* Get number of free clusters */ 25 fat = (*fatfs)->fs_type; 26 n = 0; 27 if (fat == FS_FAT12) { 28 clst = 2; 29 do { 30 stat = get_fat(*fatfs, clst); 31 if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } 32 if (stat == 1) { res = FR_INT_ERR; break; } 33 if (stat == 0) n++; 34 } while (++clst < (*fatfs)->n_fatent); 35 } else { 36 clst = (*fatfs)->n_fatent; 37 sect = (*fatfs)->fatbase; 38 i = 0; p = 0; 39 do { 40 if (!i) { 41 res = move_window(*fatfs, sect++); 42 if (res != FR_OK) break; 43 p = (*fatfs)->win; 44 i = SS(*fatfs); 45 } 46 if (fat == FS_FAT16) { 47 if (LD_WORD(p) == 0) n++; 48 p += 2; i -= 2; 49 } else { 50 if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++; 51 p += 4; i -= 4; 52 } 53 } while (--clst); 54 } 55 (*fatfs)->free_clust = n; 56 if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1; 57 *nclst = n; 58 } 59 } 60 LEAVE_FF(*fatfs, res); 61 }
函数功能:获取空闲簇的数目
描述:
f_getfree函数当 _FS_READONLY == 0并且 _FS_MINIMIZE == 0时有效。
f_getfree函数获取驱动器上空闲簇的数目。文件系统对象中的成员csize是每簇中的扇区数,因此,以扇区为单位的空闲空间可以被计算出来。当FAT32卷上的FSInfo结构不同步时,该函数返回一个错误的空闲簇计数。
例:
unsigned long total,free; if(exf_getfree("0",&total,&free)) { // 错误代码... }
1 //得到磁盘剩余容量 2 //drv:磁盘编号("0:"/"1:") 3 //total:总容量 (单位KB) 4 //free:剩余容量 (单位KB) 5 //返回值:0,正常.其他,错误代码 6 u8 exf_getfree(u8 *drv,u32 *total,u32 *free) 7 { 8 FATFS *fs1; 9 u8 res; 10 DWORD fre_clust=0, fre_sect=0, tot_sect=0; 11 //得到磁盘信息及空闲簇数量 12 res = f_getfree((const TCHAR*)drv, &fre_clust, &fs1); 13 if(res==0) 14 { 15 tot_sect=(fs1->n_fatent-2)*fs1->csize; //得到总扇区数 16 fre_sect=fre_clust*fs1->csize; //得到空闲扇区数 17 #if _MAX_SS!=512 //扇区大小不是512字节,则转换为512字节 18 tot_sect*=fs1->ssize/512; 19 fre_sect*=fs1->ssize/512; 20 #endif 21 *total=tot_sect>>1; //单位为KB 22 *free=fre_sect>>1; //单位为KB 23 } 24 return res; 25 }
FATFS 初学之 f_getfree
时间: 2024-11-11 01:20:51