i'm attempting create fat file system understand basic principle of how supposed set , i'm using struct each fat entry
struct fatentry { char name[20]; /* name of file */ uint32_t pos; /* position of file on disk (sector, block, else) */ uint32_t size; /* size in bytes of file */ uint32_t mtime; /* time of last modification */ };
i'm creating 2 mb file act file system. there write , read files blocks of 512 bytes each. question how can write struct file? fwrite allow me this? 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 store struct in bytes? how read this? i'm having trouble understanding when use fread
will store struct in bytes?
- yes. in c++ need explicitly cast
&entry1
(void*)
how read this?
fread((void*)&entry1,sizeof(entry1),1,file);
(but don't forget "r" flag fopen()
)
the real problem in case struct will padded compiler, efficient access. have use __attribute__((packed))
if using gcc.
[edit] code sample (c, not 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)
you can check read have written earlier:
assert(memcmp(&entry1, &entry2, sizeof(struct fatentry))==0);
the assert fail if read or write did not succeed (i didn't check this).
Comments
Post a Comment