简体   繁体   English

C,从bin文件中读取二进制文件

[英]C, fread binary from bin file

I'm pretty new to C, but I have come across a problem with fread... 我对C很陌生,但是遇到了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... 我的最终目标是从.bin文件中读取二进制文件(然后将其打印为控制台文件),但是现在我一次迈出了一步,并尝试仅读取第一位...

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! 现在,我已经在三个不同的.bin文件上进行了尝试,一个文件输出0,其他文件输出2,其他文件输出12!

Why is it outputting 2/12 when I am reading in just one 1 bit from file? 当我从文件中读取一个1位时,为什么输出2/12? Shouldn't it be a 0 or a 1? 应该不是0还是1? what am I doing wrong? 我究竟做错了什么? Thanks alot. 非常感谢。

Change the fread() call to: fread()调用更改为:

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 . 发布的代码正在将一个字节读入int

You should also check the return values from fopen() and fread() calls to ensure they were successful. 您还应该检查fopen()fread()调用的返回值,以确保它们成功。

Like @hmjd said, you should read the number of bytes necessary to fill an int value. 就像@hmjd所说的那样,您应该读取填充int值所需的字节数。 So either this way: 因此,无论哪种方式:

len = fread(&i, sizeof(int), 1, file);

or this way: 或者这样:

len = fread(&i, 1, sizeof(int), file);

The first case reads one int value (typically as 4 bytes). 第一种情况读取一个int值(通常为4个字节)。 After the call, len should be equal to 1 if the read succeeded. 调用后,如果读取成功, len应等于1。

The second case reads multiple bytes into an int value. 第二种情况将多个字节读入一个int值。 The difference is that after this call, len should be equal to sizeof(int) . 区别在于,此调用之后, len应等于sizeof(int)

Either way will work, the only difference being that the first way specifies reading a multiple-byte single object (an int ), whereas the second specifies the number of bytes to read into the object. 两种方法都可以使用,唯一的区别是第一种方法指定读取多字节的单个对象( int ),而第二种方法指定读取到对象中的字节数。 It's a subtle difference, and people will disagree which is best, of course. 这是一个细微的差异,人们当然会认为这是最好的。

The advantage of the second method is that len tells you exactly how many bytes were actually read (which might be useful for debugging I/O errors). 第二种方法的优点是len告诉您确切地实际读取了多少字节(这对于调试I / O错误可能很有用)。 The advantage of the first method is that it's a conceptually simpler test for success (was one int read or not?). 第一种方法的优点在于,它是从概念上讲更简单的成功测试(是否读取过int ?)。

But no matter how you do it, you should always check the return value of fread() . 但是,无论如何执行,都应始终检查fread()的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM