我想创建一个表示整数的二进制文件。我认为该文件应该是 4 个字节。我使用Linux。怎么做? 另一个问题:如何将该文件的内容分配给 C 中的整数?
最佳答案
在标准 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;
}
这个输出:
Value is: 1
关于c - 什么是二进制文件,我该如何创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/979816/