我正在努力处理二进制文件。我有以下课程:
class __attribute__((__packed__)) FileEntry {
unsigned char filename[8];
unsigned char extension[3];
unsigned char type;
unsigned char reserved;
unsigned char tenths_of_second;
unsigned short creation_time;
unsigned short creation_date;
unsigned short last_accessed;
unsigned short high_first_cluster;
unsigned short last_modification_time;
unsigned short last_modification_date;
unsigned short low_first_cluster;
unsigned int size;
};
我也有以下方法,这是给我问题的一种方法:
void Fat16FileSystem::writeToFS() {
BootSector b(512,128,1,1,2048,0,0xf8,128,32,64,2048,4194304);
FATTable f(b.total_sectors);
FileEntry fe;
char n = 0;
memset(&fe, 0, sizeof(fe));
//memset(&fi, 0, 512);
b.WriteToFS(file);
cout << "Writing the fillers" << endl;
for (int j = 0; j < (b.bytes_per_sector - 512)/512; j++) {
fwrite(&n, 1, 512, file);
}
cout << (b.bytes_per_sector - 512)/512 << " fillers was written" << endl;
f.writeToFs(file);
cout << "Writing " << b.directory_entries << " directory entries to FS" << endl;
for (int i = 0; i < b.directory_entries; i++) {
fwrite(&fe, sizeof(fe), 1, file);
}
fflush(file);
cout << "Writing " << b.large_total_sectors << " fillers to FS";
for (long k = 0; k < b.large_total_sectors; k++) {
fwrite(&n, 1, 512, file);
}
}
它似乎一直有效,直到它写入目录条目为止,之后似乎重写了它的开头。使用十六进制编辑器,我可以看到它编写的字符与bootsector部分匹配。有人可以解释为什么吗?
最佳答案
像fwrite(&n, 1, 512, file);
这样的结构容易出错。为了避免错误,您应该从缓冲区中推断出商品的大小和商品的数量:
// ...
FILE* f = 0;
char n[512];
// ...
fwrite( n, sizeof n[0], sizeof n / sizeof n[0], f );
// ...
如果您更改
n
的类型或其大小,您仍然可以编写期望的内容。这就是缓冲区n
的内容(我不会为缓冲区使用的名称)。关于下面的评论,“不是写(写什么,写什么大小,要写多少次,写在哪里)?”。您误解了第三个参数的含义。从MSDN:fwrite函数最多写入从缓冲区到输出流的计数项,每个项的大小长度。换句话说,缓冲区的长度(以字节为单位)最多必须为
parameter2 * parameter3
。您的缓冲区是1个字节(char n
),但是您写入了512个字节。由于您要求fwrite
超出缓冲区的大小,因此,这很可能就是垃圾的根源。关于c++ - 尝试写入二进制文件时出现垃圾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35283971/