0

I'm attempting to create a FAT file system I understand the basic principle of how its supposed to set up and I'm using a struct like this for each FAT entry

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 */
};

I'm essentially creating a 2 MB file to act as my file system. From there I will write and read files into blocks of 512 bytes each. My question how I can write a struct to a file? Does fwrite allow me to do this? For example:

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);

Will that store the struct in bytes? How do I read from this? I'm having trouble understanding what I will get back when I use fread

4

1 回答 1

1

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

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

我如何从中阅读?

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

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

在您的情况下,真正的问题是结构可能会被编译器填充,以便有效访问。因此,__attribute__((packed))如果您使用 gcc,则必须使用。

[编辑] 代码示例(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);

如果读取或写入不成功,则断言将失败(我没有检查这一点)。

于 2013-05-06T00:35:24.750 回答