读取二进制文件会导致垃圾值

时间:2014-03-06 02:01:12

标签: c

#include<stdio.h>
#include<stdlib.h>
int main()
{
 int *buffer;
 int i;
 FILE *fp;
 buffer=(int *)malloc(256);
fp=fopen("BACKING_STORE.bin", "r");  //BACKING_STORE.bin is a binary file of size 65K bytes
fseek(fp, 0, SEEK_SET);              //and I am trying to read 256 bytes at a time and storing 
fread(buffer, 256, 1, fp);           //it into buffer of size 256 bytes and printing that buffer
 printf("Data=%d\n", buffer);        //on screen.

 fclose(fp);
}

当我运行这个程序时,我得到了垃圾值。我知道这是因为在fseek()函数中我改变了偏移量。就像第一次当我将偏移量设为0时,它给出了一些值,比如12342539然后我将偏移量更改为256,它将输出设置为14562342,再次将偏移设置为0时,它给出了不同的输出15623478。 所以这就是它显示输出是垃圾的方式。

2 个答案:

答案 0 :(得分:2)

您没有打印缓冲区的内容,而是打印其地址(截断/强制转换为int)。变化:

printf("Data=%d\n", buffer);

为:

printf("Data=%d\n", buffer[0]);

甚至

printf("Data=%d %d %d %d...\n", buffer[0], buffer[1], buffer[2], buffer[3]);

其他注意事项:

  • 不要将malloc的结果投射到C中 - 它是unnecessary and potentially dangerous

  • 打开二进制文件时,
  • 使用"rb"而不是"r" - 这在大多数平台上都无关紧要,但在Windows上可能会出现问题

  • 始终启用编译器警告(例如gcc -Wall ...) - 这将使您能够在编译时立即识别并修复错误,而不是在运行时对意外输出感到困惑

答案 1 :(得分:1)

试试这个

buffer=malloc(256);
fp=fopen("BACKING_STORE.bin", "rb");
fread(buffer, 256, 1, fp);
fclose(fp);
printf("Data=\n");
for(i = 0; i<256/sizeof(int);++i){
    printf("%d\n", buffer[i]);
}
free(buffer);