我是 C 的新手,正如标题所说,我正在尝试编写一个简单的程序来读写二进制文件。代码如下:
#include<stdio.h>
int main(void){
FILE *fd = fopen("binFile.bin", "wb");
if(fd == NULL){
printf("Failed to open/create file.\n");
return -1;
}
char buff1[] = "#This is a comment.\n";
fwrite(buff1,1,sizeof(buff1),fd);
char buff2[] = "#This is another comment.\n";
fwrite(buff2,1,sizeof(buff2),fd);
int i;
float f[3];
for(i=0; i<100; i++){
f[0] = i-1;
f[1] = i;
f[2] = i+1;
fwrite(f,sizeof(f),1,fd);
}
fclose(fd);
fd = fopen("binFile.bin", "rb");
if(fd == NULL){
printf("Failed to read file.\n");
return -1;
}
char buff[100];
do{
fread(buff,1,sizeof(buff),fd);
printf("%s",buff);
}
while(!feof(fd));
fclose(fd);
return 0;
}
当我运行这段代码时,它只打印:
#This is a comment.
我知道我没有对文件使用一堆检查;但是,我认为问题在于我正在尝试使用相同的缓冲区读取 char 和 float,因为仅对 char(或仅 float)使用相同的代码工作得很好。我猜我必须以某种方式知道 char 的字节和 float 的字节从哪里开始相应地调整我的缓冲区大小/类型。
我希望我能充分解释自己。任何帮助表示赞赏。
最佳答案
看看你的二进制文件
如您所见,在字节 14h 处有一个空终止符,就在“This is a comment.\n”字符串之后。
这是因为您在用字符串文字初始化的 char 数组上使用了 sizeof(buff1)
,这样的文字总是包含空终止符。
另请注意,您存储的 float 是二进制格式,如果您的系统使用 IEEE754(我的也是),当您编写 -1 时,编码为 0bf800000h
.
这导致文件中的字节值为 0,此类字节也将被解释为空终止符。
关于c - 使用 char 和 float 读取\写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31526804/