我想创建一个表示整数的二进制文件。我认为该文件应该是 4 个字节。我使用Linux。怎么做?另一个问题:如何将该文件的内容分配给 C 中的整数?
confucious
问问题
56249 次
4 回答
16
在标准 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
于 2009-06-11T07:46:09.483 回答
4
从操作系统的角度来看,所有文件都是二进制文件。C(和 C++)提供了一种特殊的“文本模式”,可以将换行符扩展为换行符/回车符对(在 Windows 上),但操作系统不知道这一点。
在 C 程序中,要创建没有这种特殊处理的文件,请使用 fopen() 的“b”标志:
FILE * f = fopen("somefile", "wb" );
于 2009-06-11T07:50:17.243 回答
3
打开文件进行二进制读/写。fopen 需要一个b
文件访问模式参数的开关 -见这里
有关文本和二进制文件之间的区别以及将数据写入二进制文件的代码示例,请参见Wikipedia 中的 fopen 页面
于 2009-06-11T07:43:27.290 回答
1
参见系统man
调用open
和。write
read
于 2009-06-11T07:47:52.273 回答