FatFS是一个适用于小型嵌入式系统的通用的FAT/exFAT文件系统模块。FatFS是使用ANSI C(C89)进行编写的,并且分出了磁盘I/O层,因此它是独立于平台的。不仅仅可以用于各种嵌入式平台,同样台用于Linux、android、MacOS甚至windows平台。
主要代码文件:
本文的内容及示例均是基于ff1.4版本进行的,并且在Windows平台上,基于虚拟磁盘和真实U盘进行测试和验证的。
以下设置为示例使用设置,为了更方便测试,没有启用Unicode及多分区功能。
// 此函数主要完成磁盘设备的打开(虚拟磁盘文件的创建打开)
int assign_drives();
// 此函数返回磁盘是否写保护状态
DSTATUS disk_status (BYTE pdrv);
// 此函数的作用是完成获取磁盘的容量、扇区大小(虚拟磁盘直接写死即可)
DSTATUS disk_initialize (BYTE pdrv);
// 此函数主要负责读取磁盘指定位置指定大小的内容
DRESULT disk_read (BYTE pdrv, BYTE* buff, LBA_t sector, UINT count);
// 此函数主要负责往磁盘指定位置写入指定大小的内容
DRESULT disk_write (BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count);
// 此函数主要根据cmd来返回指定内容,如扇区大小、容量、对齐扇区大小
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
/*-----------------------------------------------------------------------*/
/* Initialize Disk Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber */
)
{
DSTATUS sta;
if (WaitForSingleObject(hMutex, 5000) != WAIT_OBJECT_0)
{
return STA_NOINIT;
}
get_status(pdrv);
sta = Stat[pdrv].status;
ReleaseMutex(hMutex);
return sta;
}
/*-----------------------------------------------------------------------*/
/* Get Disk Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE pdrv /* Physical drive nmuber (0) */
)
{
DSTATUS sta;
sta = Stat[pdrv].status;
return sta;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber (0) */
BYTE *buff, /* Pointer to the data buffer to store read data */
LBA_t sector, /* Start sector number (LBA) */
UINT count /* Number of sectors to read */
)
{
DWORD nc = 0, rnc;
DSTATUS res;
UINT uPartIdx = 0;
UINT uPartCnt = (count+127) / 128;
UINT uBuffSct = 128;
if (Stat[pdrv].status & STA_NOINIT || WaitForSingleObject(hMutex, 3000) != WAIT_OBJECT_0)
{
return RES_NOTRDY;
}
nc = (DWORD)count * Stat[pdrv].sz_sector;
memcpy(Buffer, buff, nc);
for (; uPartIdx < uPartCnt; uPartIdx++)
{
// 如果是最后1份,且是不完整的
if (uPartIdx == (count / 128))
{
uBuffSct = count % 128;
}
if (!LogReadFlash(Stat[pdrv].h_drive, sector, uBuffSct, Buffer, 512))
{
res = RES_ERROR;
}
else
{
memcpy(buff + uPartIdx*128*512, Buffer, nc);
res = RES_OK;
}
sector += uBuffSct;
}
ReleaseMutex(hMutex);
return res;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber (0) */
const BYTE *buff, /* Pointer to the data to be written */
LBA_t sector, /* Start sector number (LBA) */
UINT count /* Number of sectors to write */
)
{
DWORD nc = 0, rnc;
LARGE_INTEGER ofs;
DRESULT res;
if (Stat[pdrv].status & STA_NOINIT || WaitForSingleObject(hMutex, 3000) != WAIT_OBJECT_0)
{
return RES_NOTRDY;
}
res = RES_OK;
if (Stat[pdrv].status & STA_PROTECT)
{
res = RES_WRPRT;
}
else
{
nc = (DWORD)count * Stat[pdrv].sz_sector;
if (nc > BUFSIZE) res = RES_PARERR;
}
/* Physical drives */
if (pdrv >= MIN_READ_ONLY && pdrv <= MAX_READ_ONLY)
res = RES_WRPRT;
if (res == RES_OK)
{
UINT uPartIdx = 0;
UINT uPartCnt = (count+127) / 128;
UINT uBuffSct = 128;
memcpy(Buffer, buff, nc);
for (; uPartIdx < uPartCnt; uPartIdx++)
{
// 如果是最后1份,且是不完整的
if (uPartIdx == (count / 128))
{
uBuffSct = count % 128;
}
if (!LogWriteFlash(Stat[pdrv].h_drive, sector, uBuffSct, Buffer, 512))
{
res = RES_ERROR;
}
sector += uBuffSct;
}
}
ReleaseMutex(hMutex);
return res;
}
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0) */
BYTE ctrl, /* Control code */
void *buff /* Buffer to send/receive data */
)
{
DRESULT res;
if ((Stat[pdrv].status & STA_NOINIT))
{
return RES_NOTRDY;
}
res = RES_PARERR;
switch (ctrl)
{
case CTRL_SYNC: /* Nothing to do */
res = RES_OK;
break;
case GET_SECTOR_COUNT: /* Get number of sectors on the drive */
*(LBA_t*)buff = Stat[pdrv].n_sectors;
res = RES_OK;
break;
case GET_SECTOR_SIZE: /* Get size of sector for generic read/write */
*(WORD*)buff = Stat[pdrv].sz_sector;
res = RES_OK;
break;
case GET_BLOCK_SIZE: /* Get internal block size in unit of sector */
*(DWORD*)buff = SZ_BLOCK;
res = RES_OK;
break;
case 200: /* Load disk image file to the RAM disk (drive 0) */
{
HANDLE h;
DWORD br;
if (pdrv == 0)
{
h = CreateFileW(buff, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (h != INVALID_HANDLE_VALUE)
{
if (ReadFile(h, RamDisk, SZ_RAMDISK * 1024 * 1024, &br, 0))
{
res = RES_OK;
}
CloseHandle(h);
}
}
}
break;
}
return res;
}
int get_status (
BYTE pdrv
)
{
volatile STAT *stat = &Stat[pdrv];
/* Get drive size */
stat->status = STA_NOINIT;
stat->sz_sector = 512;
stat->n_sectors = 15761504;
if (stat->sz_sector < FF_MIN_SS || stat->sz_sector > FF_MAX_SS)
return 0;
/* Get write protect status */
stat->status = 0;
if (pdrv >= MIN_READ_ONLY && pdrv <= MAX_READ_ONLY) stat->status = STA_PROTECT;
return 1;
}
/*--------------------------------------------------------------------------
Public Functions
---------------------------------------------------------------------------*/
#define FILENAME "e:\\Virtual.img"
/*-----------------------------------------------------------------------*/
/* Initialize Windows disk accesss layer */
/*-----------------------------------------------------------------------*/
int assign_drives (void)
{
BYTE pdrv = 0;
HANDLE h;
DWORD dwRet = 0;
OSVERSIONINFO vinfo = { sizeof (OSVERSIONINFO) };
hMutex = CreateMutex(0, 0, 0);
if (hMutex == INVALID_HANDLE_VALUE)
return 0;
Buffer = VirtualAlloc(0, BUFSIZE, MEM_COMMIT, PAGE_READWRITE);
if (!Buffer) return 0;
RamDisk = VirtualAlloc(0, SZ_RAMDISK * 0x100000, MEM_COMMIT, PAGE_READWRITE);
if (!RamDisk)
return 0;
Stat[0].h_drive = fopen(FILENAME, "w+");
if (!Stat[0].h_drive)
{
printf(__FILE__":%d\n", __LINE__);
printf(FILENAME" open err!\n");
return RES_NOTRDY;
}
wprintf(L"PD#%u <== %s", 0, "virtual disk");
if (get_status(0))
{
wprintf(L" (%uMB, %u bytes * %I64u sectors)\n", (UINT)((LONGLONG)Stat[pdrv].sz_sector * Stat[pdrv].n_sectors / 1024 / 1024), Stat[pdrv].sz_sector, (QWORD)Stat[pdrv].n_sectors);
}
else
{
wprintf(L" (Not Ready)\n");
}
Drives = 0;
return 0;
}
/*-----------------------------------------------------------------------*/
/* Initialize Disk Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber */
)
{
DSTATUS sta;
if (WaitForSingleObject(hMutex, 5000) != WAIT_OBJECT_0)
{
return STA_NOINIT;
}
get_status(pdrv);
sta = Stat[pdrv].status;
ReleaseMutex(hMutex);
return sta;
}
/*-----------------------------------------------------------------------*/
/* Get Disk Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE pdrv /* Physical drive nmuber (0) */
)
{
DSTATUS sta;
sta = Stat[pdrv].status;
return sta;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber (0) */
BYTE *buff, /* Pointer to the data buffer to store read data */
LBA_t sector, /* Start sector number (LBA) */
UINT count /* Number of sectors to read */
)
{
DWORD nc, rnc;
LARGE_INTEGER ofs;
DSTATUS res = 0;
DWORD ulSeek = 0;
unsigned long nRead = 0;
int nSeekRes = 0;
ulSeek = sector * 512;
nSeekRes = fseek(Stat[pdrv].h_drive, ulSeek, SEEK_SET);
nRead = fread(buff, 512, count, Stat[pdrv].h_drive);
if (nSeekRes || nRead == 0) {
printf(__FILE__":%d\n", __LINE__);
printf("read disk err!\n");
return RES_ERROR;
}
return res;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber (0) */
const BYTE *buff, /* Pointer to the data to be written */
LBA_t sector, /* Start sector number (LBA) */
UINT count /* Number of sectors to write */
)
{
DWORD nc = 0, rnc;
LARGE_INTEGER ofs;
DRESULT res;
DWORD ulSeek = 0;
unsigned long nRead = 0;
int nSeekRes = 0;
ulSeek = sector * 512;
res = RES_OK;
if (Stat[pdrv].status & STA_PROTECT)
{
res = RES_WRPRT;
}
else
{
nc = (DWORD)count * Stat[pdrv].sz_sector;
if (nc > BUFSIZE) res = RES_PARERR;
}
nSeekRes = fseek(Stat[pdrv].h_drive, ulSeek, SEEK_SET);
nRead = fwrite(buff, 512, count, Stat[pdrv].h_drive);
if (nSeekRes || nRead == 0)
{
printf(__FILE__":%d\n", __LINE__);
printf("read disk err!\n");
return RES_ERROR;
}
return res;
}
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0) */
BYTE ctrl, /* Control code */
void *buff /* Buffer to send/receive data */
)
{
DRESULT res;
res = RES_PARERR;
switch (ctrl)
{
case CTRL_SYNC: /* Nothing to do */
res = RES_OK;
break;
case GET_SECTOR_COUNT: /* Get number of sectors on the drive */
*(LBA_t*)buff = Stat[pdrv].n_sectors;
res = RES_OK;
break;
case GET_SECTOR_SIZE: /* Get size of sector for generic read/write */
*(WORD*)buff = Stat[pdrv].sz_sector;
res = RES_OK;
break;
case GET_BLOCK_SIZE: /* Get internal block size in unit of sector */
*(DWORD*)buff = SZ_BLOCK;
res = RES_OK;
break;
case 200: /* Load disk image file to the RAM disk (drive 0) */
{
HANDLE h;
DWORD br;
if (pdrv == 0)
{
h = CreateFileW(buff, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (h != INVALID_HANDLE_VALUE)
{
if (ReadFile(h, RamDisk, SZ_RAMDISK * 1024 * 1024, &br, 0))
{
res = RES_OK;
}
CloseHandle(h);
}
}
}
break;
}
return res;
}
FatFS应用接口,主要分四大类:
示例完全基于ff1.4版本,只修改磁盘I/O接口,完全不修改ff.c代码。
// 3就是设备号,在FatFS中也被称为逻辑驱动器号,默认不填写则为0
TCHAR filePath[] = "3:\\hello.txt";
MKFS_PARM opt = {0};
FATFS fsEx = {0};
FRESULT fRet = FR_OK;
assign_drives('j', 3);
f_mount(&fsEx, "3:", 0);
opt.fmt = FM_EXFAT;
opt.n_fat = 2;
fRet = f_mkfs("3:", &opt, workBuff, sizeof(workBuff));
FIL fil = {0};
FRESULT res = FR_OK;
UINT bw = 0;
BYTE buff[1024] = {0};
res = f_open(&fil, pFilePath, FA_CREATE_NEW | FA_WRITE);
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
f_write(&fil, "Hello, World!\n", 15, &bw);
if (bw != 15)
{
printf("f_write hello.txt err\n");
f_close(&fil);
return 1;
}
f_close(&fil);
res = f_open(&fil, pFilePath, FA_READ | FA_OPEN_EXISTING);
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
memset(buff, 0, sizeof(buff));
res = f_read(&fil, buff, 15, &bw);
if (res)
{
printf("f_read err\n");
f_close(&fil);
return res;
}
printf("buff: %s", buff);
UINT bw = 0;
FIL fil = {0};
TCHAR buff[1024] = {0};
DIR dir = {0};
FRESULT res = FR_OK;
res = f_mkdir("3:\\ABC");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_opendir(&dir, "3:\\ABC");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_mkdir("3:\\ABC\\A");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_opendir(&dir, "3:\\ABC\\A");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_mkdir("3:\\ABC\\B");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_opendir(&dir, "3:\\ABC\\B");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_mkdir("3:\\ABC\\B\\C");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
res = f_opendir(&dir, "3:\\ABC\\B\\C");
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
f_closedir(&dir);
res = f_open(&fil, "3:/ABC/B/a.txt", FA_CREATE_NEW | FA_WRITE);
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
f_write(&fil, "Mike say:Hello, World!\n", 24, &bw);
if (bw != 24)
{
printf("f_write hello.txt err\n");
f_close(&fil);
return 1;
}
f_close(&fil);
res = f_open(&fil, "3:/ABC/B/a.txt", FA_READ | FA_OPEN_EXISTING);
if (res)
{
printf("f_open hello.txt err\n");
return res;
}
memset(buff, 0, sizeof(buff));
res = f_read(&fil, buff, 24, &bw);
if (res)
{
printf("f_read err\n");
f_close(&fil);
return res;
}
printf("buff: %s", buff);
f_close(&fil);
FRESULT scan_files (
CHAR* path /* Pointer to the path name working buffer */
)
{
DIR dir;
FRESULT res;
int i;
if ((res = f_opendir(&dir, path)) == FR_OK)
{
i = strlen(path);
while (((res = f_readdir(&dir, &Finfo)) == FR_OK) && Finfo.fname[0])
{
if (Finfo.fattrib & AM_DIR)
{
AccDirs++;
*(path+i) = L'/';
strcpy(path+i+1, Finfo.fname);
printf("%s\n", path);
res = scan_files(path);
*(path+i) = L'\0';
if (res != FR_OK)
break;
}
else
{
AccFiles++;
AccSize += Finfo.fsize;
printf("%s\n", Finfo.fname);
}
}
f_closedir(&dir);
}
return res;
}
多分区需要启用宏FF_MULTI_PARTITION。
int TestMultiParition()
{
#if FF_MULTI_PARTITION
FRESULT fRet = FR_OK;
MKFS_PARM opt = {0};
LBA_t plist[] = {3000*2048, 100}; /* Divide the drive into two partitions */
/* {0x10000000, 100}; 256M sectors for 1st partition and left all for 2nd partition */
/* {20, 20, 20, 0}; 20% for 3 partitions each and remaing space is left not allocated */
f_fdisk(0, plist, workBuff); /* Divide physical drive 0 */
opt.fmt = FM_FAT32;
opt.n_fat = 2;
fRet = f_mkfs("0:", &opt, workBuff, sizeof(workBuff)); /* Create FAT volume on the logical drive 0 */
fRet = f_mkfs("1:", &opt, workBuff, sizeof(workBuff)); /* Create FAT volume on the logical drive 1 */
#endif
return 0;
}
我们可以通过虚拟盘将文件系统及相关信息写入到Windows的文件中,用文件来模拟FatFS的移植。创建format.img文件,将diskio的相关接口均实现到此文件中。并且通过DiskGunius工具提供的打开虚拟磁盘文件,可以查看相关信息。DiskGunius支持FAT32和exFAT文件系统。
Windows下基于文件仿真FatFS
基于Windows下的真实U盘的FatFS