擅长:python、mysql、java
<p>一些C代码:</p>
<pre><code>#include <stdio.h>
typedef struct { double v; int t; char c;} save_type;
int main() {
save_type s = { 12.1f, 17, 's'};
FILE *f = fopen("output", "w");
fwrite(&s, sizeof(save_type), 1, f);
fwrite(&s, sizeof(save_type), 1, f);
fwrite(&s, sizeof(save_type), 1, f);
fclose(f);
return 0;
}
</code></pre>
<p>一些Python代码:</p>
<pre><code>import struct
with open('output', 'rb') as f:
chunk = f.read(16)
while chunk != "":
print len(chunk)
print struct.unpack('dicccc', chunk)
chunk = f.read(16)
</code></pre>
<p><em>输出</em>:</p>
<pre><code>(12.100000381469727, 17, 's', '\x00', '\x00', '\x00')
(12.100000381469727, 17, 's', '\x00', '\x00', '\x00')
(12.100000381469727, 17, 's', '\x00', '\x00', '\x00')
</code></pre>
<p>但也有填充问题。<code>save_type</code>的填充大小是16,因此我们又读取了3个字符并忽略它们。</p>