如何在C中实现FAT?

7d7tgy0s  于 2023-10-16  发布在  其他
关注(0)|答案(2)|浏览(124)

我有disc.img,这是Linux中的fat32文件系统。我想达到它的FAT和计算出每个文件使用的块。我读过http://wiki.osdev.org/FAT#FAT_32_3,但不知道如何到达table。也许我错过了什么。
我如何才能到达FAT?

pbgvytdp

pbgvytdp1#

你需要读取 Boot 扇区。一旦你有了这些信息,http://wiki.osdev.org/FAT#Reading_the_Boot_Sector会告诉你如何到达FAT:
文件分配表中的第一个扇区:first_fat_sector = fat_boot->reserved_sector_count;

hujrc8aj

hujrc8aj2#

这是一个视频的例子。视频链接在此代码下。

#include <stdio.h>
#include <stdbool.h>
// The stdbool.h is a POSIX library that defines type bool, and constants true and false that stands for 1 and 0 consecutively. 

typedef struct {
    uint8_t BootJumpInstruction[3];
    uint8_t OemIdentifier[8];
    uint16_t BytesPerSector;
    uint8_t SectorsPerCluster;
    uint16_t ReservedSectors;
    uint8_t FatCount;
    uint16_t DirEntryCount;
    uint16_t TotalSectors;
    uint8_t MediaDescriptorType;
    uint16_t SectorsPerFat;
    uint16_t SectorsPerTrack;
    uint16_t Heads;
    uint32_t HiddenSectors;
    uint32_t LargeSectors;

    // extended boot record
    uint8_t DriveNumber;
    uint8_t WindowsNTFlags;
    uint8_t Signature;
    uint32_t VolumeId;
    uint8_t VolumeLabel[11];
    uint8_t SystemIdentifier[8];
} __attribute__((packed)) BootSector;
/* (Note: here can be found `__attribute__((packed))`, it works for gcc, for other compilers and/or debuggers - IDK (I don't know) 🫣... */

BootSector g_BootSector;
uint8_t *g_Fat = NULL;

bool readBootSector(FILE *disk)
{
    return fread(&g_BootSector, sizeof(g_BootSector), 1, disk);
}

bool readSectors(FILE *disk, uint32_t lba, uint32_t count, void *bufferOut)
{
    bool ok = true;
    ok = ok && (fseek(disk, lba * g_BootSector.BytesPerSector, SEEK_SET == 0));
    ok = ok && (fread(bufferOut, g_BootSector.BytesPerSector, count, disk) == count);
    return ok;
}

bool readFat(FILE *disk)
{
    g_Fat = (uint8_t *)malloc(g_BootSector.SectorsPerFat * g_BootSector.BytesPerSector);
    return readSectors(disk, g_BootSector.ReservedSectors, g_BootSector.SectorsPerFat, g_Fat);
}

int main(int argc, char **argv)
{

    if (argc < 3)
    {

        printf("Syntax: %s <disk image> <file name>\n", argv[0]);
        return -1;

    }

    FILE *disk = fopen(argv[1], "rb");

    if (!disk)
    {

        fprintf(stderr, "Cannot open disk image %s!", argv[1]);
        return -1;

    }

    if (!readBootSector(disk))
    {

        fprintf(stderr, "Could not read boot sector!");
        return -2;

    }

    if (!readFat(disk))
    {

        fprintf(stderr, "Could not read FAT!");
        free(g_Fat);
        return -3;

    }

    free(g_Fat);
    return 0;
}

这是一个video(实际上它是一个播放列表,您的案例所需的视频是第3个,关于FAT文件系统),我正在观看并制作操作系统。

相关问题