#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。 这就是它显示垃圾输出的方式。
最佳答案
您不是在打印缓冲区的内容,而是在打印其地址(截断/转换为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]);
其他注意事项:
不要在 C 中转换
malloc
的结果 - 它是 unnecessary and potentially dangerous在打开二进制文件时使用
"rb"
而不是"r"
- 这在大多数平台上无关紧要,但在 Windows 上可能是个问题始终启用编译器警告(例如
gcc -Wall ...
)- 这将使您能够在编译时立即识别并修复错误,而不是对意外输出感到困惑在运行时
关于c - 读取二进制文件导致垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22213365/