【问题标题】:Attempting to create a FAT file system in C++?尝试在 C++ 中创建 FAT 文件系统?
【发布时间】:2013-04-29 17:21:20
【问题描述】:

我正在尝试创建一个 FAT 文件系统,我了解它应该如何设置的基本原理,并且我正在为每个 FAT 条目使用这样的结构

struct FATEntry
{
    char      name[20];  /* Name of file */
    uint32_t  pos;       /* Position of file on disk (sector, block, something else) */
    uint32_t  size;      /* Size in bytes of file */
    uint32_t  mtime;     /* Time of last modification */
};

我实际上是在创建一个 2 MB 的文件来充当我的文件系统。从那里我会将文件写入和读取到每个 512 字节的块中。我的问题是如何将结构写入文件? fwrite 允许我这样做吗?例如:

struct FATEntry entry1;
strcpy(entry1.name, "abc");
entry1.pos = 3;
entry1.size = 10;
entry1.mtime = 100;
cout << entry1.name;

file = fopen("filesys", "w");
fwrite(&entry1,sizeof(entry1),1,file);
fclose(file);

这会以字节为单位存储结构吗?我如何从中阅读?我无法理解使用 fread 会得到什么

【问题讨论】:

    标签: c++ filesystems fat


    【解决方案1】:

    这会以字节为单位存储结构吗?

    • 是的。在 C++ 中,您需要将 &amp;entry1 显式转换为 (void*)

    我如何从中读取?

    • fread((void*)&amp;entry1,sizeof(entry1),1,file);

    (但不要忘记 fopen() 的“r”标志)

    在您的情况下,真正的问题是结构will probably be padded by the compiler,用于有效访问。因此,如果您使用 gcc,则必须使用 __attribute__((packed))

    [编辑] 代码示例(C,不是 C++):

    struct FATEntry entry1 { "abc", 3, 10, 100 };
    FILE* file1 = fopen("filesys", "wb");
    fwrite(&entry1, sizeof(struct FATEntry), 1, file1);
    fclose(file1)
    
    struct FATEntry entry2 { "", 0, 0, 0 };
    FILE* file2 = fopen("filesys", "rb");
    fread(&entry2, sizeof(struct FATEntry), 1, file2;
    fclose(file2)
    

    您现在可以检查您是否阅读了之前写的内容:

    assert(memcmp(&entry1, &entry2, sizeof(struct FATEntry))==0);
    

    如果读取或写入不成功,assert 将失败(我没有对此进行检查)。

    【讨论】:

    • 谢谢,但是 fread((void*)&entry1,sizeof(entry1),1,file);返回?一个结构?我认为这让我感到困惑。
    • fread 返回“成功读取的元素总数”。这可能比你的意思要少。它将用实际数据填充entry1
    • 哎呀 - 我忘了提到你也需要使用“b”标志 - 你正在处理原始数据,而不是文本。
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2017-04-14
    • 2016-02-10
    • 2016-09-10
    • 1970-01-01
    • 2013-03-20
    • 2011-11-27
    • 1970-01-01
    相关资源
    最近更新 更多