首页 > 解决方案 > 读取 FAT32 中的目录内容

问题描述

我正在尝试在 RPI 3B 上编写裸机 FAT32 文件系统驱动程序。我能够使用 emmc 驱动程序读取 FAT 扇区和根目录扇区。

当下一个条目指针(下一个簇号)不适合当前的 FAT 扇区时,​​我对如何遵循 FAT 条目链表有疑问?每次获得新的簇号时是否应该读取 FAT 扇区?

我目前的理解如下: 获取目录/文件的第一个簇号(cluster_number) 读取包含 first_cluster_number 条目的 FAT 扇区。假设我将 FAT 扇区读为

uint8_t fat_sector[512] = { 0 };
uint32_t this_fat_sector_num, this_fat_entry_offset;
this_fat_sector_num =  unusedSectors + reservedSectorCount + ((cluster_number * 4)/ bytesPerSector);
this_fat_entry_offset =  (cluster_number * 4)/ bytesPerSector;
read_fat_sector(this_fat_sector_num, & fat_sector[0]);
// Calculate next cluster in chain
uint32_t next_cluster_number = ((uint32_t * fat_sector[this_fat_entry_offset])) & 0x0fffffff;
// Calculate next cluster in chain 1 more time, is below code correct ?
 uint32_t next_next_cluster_number = ((uint32_t * fat_sector[next_cluster_number])) & 0x0fffffff;

当已经读取的 fat_sector 缓冲区(512 字节)中不存在下一个簇号时会发生什么?如果簇号 = fat_sector 中下一个条目的索引,鉴于 fat 32 条目跨越 4 个字节,我是否需要将其乘以 4。如果有人能给出一些明确的说明,那将很有帮助。提前致谢。

标签: osdevfat32fatfs

解决方案


实现 FAT 的缓存(在 RAM 中)。假设缓存有足够的 RAM 用于 20 个扇区并且开始时是空的。

接下来编写一个“getFATentry”函数,检查该扇区是否在缓存中,如果在,则在缓存中找到正确的条目;或者(如有必要)从缓存中清除某些内容以腾出空间,从磁盘中获取正确的扇区到缓存中,然后在缓存中找到正确的条目。

一旦完成,您就可以next_cluster = getFATentry(previous_cluster);不用担心缓存或任何磁盘 IO(但在修改 FAT 时会想要做一些事情 - 例如采用“直写”或“回写”策略)。

注意:通过调整“FAT 缓存”的大小,您可以提高性能或减少 RAM 消耗。允许缓存动态增长/收缩会很好(例如,如果没有其他东西需要RAM,则增长到与整个FAT一样大,但如果其他东西需要所有RAM,则缩小到最低限度)。


推荐阅读