我试图在文件中写入4个无符号整数的结构,然后将其读回,但无法读取任何内容。从文件中读取结构
这里是我的代码:
// create and write values in superblock
..
Superblock s; // the struct
if(write(file_desc , &superblock , sizeof(Superblock)) == -1) {
perror("writing superblock");
exit(1);
}
close(file_desc);
file_desc = open(path_file, O_WRONLY | O_CREAT, 0600);
while ((read(file_desc , &s , sizeof(Superblock))) > 0) {
printf("%u %u %u %u\n", s.block_size, s.filename_size, s.max_file_size,
s.max_dir_file_no);
}
它甚至不会进入循环。我错过了什么?
直接读/写结构到磁盘是一个坏主意。它们可以包含高度依赖于编译器的填充。 – unwind 2015-02-06 15:21:57
是的,最好直接序列化结构的每个字段,以便控制哪些位是外部表示的一部分。通过直接写入整个结构,你没有这种控制。 – unwind 2015-02-06 15:27:48
我明白了@unwind。 – gsamaras 2015-02-06 15:27:49