gpt4 book ai didi

c++ - 试图用 C++ 创建 FAT 文件系统?

转载 作者:行者123 更新时间:2023-11-28 07:37:48 24 4
gpt4 key购买 nike

我正在尝试创建一个 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 字节的 block 中。我的问题是如何将结构写入文件? 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++ 中,您需要将 &entry1 显式转换为 (void*)

我该如何阅读?

  • fread((void*)&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如果读取或写入不成功,将会失败(我没有检查这一点)。

关于c++ - 试图用 C++ 创建 FAT 文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com