我想创建一个表示整数的二进制文件.我认为该文件应该是4个字节.我用linux.怎么做?另一个问题:如何将该文件的内容分配给C中的整数?
pax*_*blo 14
在标准C中,fopen()允许模式"wb"以"rb"二进制模式写入(和读取),因此:
#include <stdio.h>
int main() {
/* Create the file */
int x = 1;
FILE *fh = fopen ("file.bin", "wb");
if (fh != NULL) {
fwrite (&x, sizeof (x), 1, fh);
fclose (fh);
}
/* Read the file back in */
x = 7;
fh = fopen ("file.bin", "rb");
if (fh != NULL) {
fread (&x, sizeof (x), 1, fh);
fclose (fh);
}
/* Check that it worked */
printf ("Value is: %d\n", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这输出:
Value is: 1
Run Code Online (Sandbox Code Playgroud)