C,从bin文件中读取二进制文件 [英] C, fread binary from bin file
问题描述
我刚接触C,但是遇到了fread问题...
我的最终目标是从.bin文件中读取二进制文件(然后将其打印为控制台文件),但现在我一次只将其迈出一步,并尝试仅读取第一位... >
我的代码:
...
FILE *file = fopen("test1.bin", rb);
int i = 0;
fread(&i, 1, 1, file);
printf("%i\n", i);
...
现在我已经在三个不同的.bin文件上进行了尝试,一个文件输出0,其他文件输出2,其他文件输出12!
当我仅从文件中读取1位时,为什么它输出2/12?它不应该是0或1吗?我究竟做错了什么?非常感谢.
更改> c0> 呼叫:
fread(&i, sizeof(int), 1, file);
第二个参数是要读取的元素的大小,第三个参数是要读取的元素的数目.发布的代码正在将单个字节读入int
.
您还应该检查fopen()
和fread()
调用的返回值,以确保它们成功.
I'm pretty new to C, but I have come across a problem with fread...
My end goal is to read (and then printf to console) the binary from a .bin file, but for now i'm taking it one step at a time and trying to just read the first bit...
My code:
...
FILE *file = fopen("test1.bin", rb);
int i = 0;
fread(&i, 1, 1, file);
printf("%i\n", i);
...
Now i've tried this on three different .bin files, one outputted 0, other 2 and the other 12!
Why is it outputting 2/12 when I am reading in just one 1 bit from file? Shouldn't it be a 0 or a 1? what am I doing wrong? Thanks alot.
Change the fread()
call to:
fread(&i, sizeof(int), 1, file);
The second argument is the size of an element to read, the third argument is the number of elements to read. The posted code is reading a single byte into an int
.
You should also check the return values from fopen()
and fread()
calls to ensure they were successful.
这篇关于C,从bin文件中读取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!