简体   繁体   English

如何使用fread从二进制文件中读取整数?

[英]How do I read an integer from a binary file using fread?

I've realized that my much bigger file is failing because it can't properly read the first integer in a binary file. 我意识到我更大的文件失败了,因为它无法正确读取二进制文件中的第一个整数。 This is my test file I've set up to do only that. 这是我设置的测试文件,仅用于此。 I know that the int I'm reading will always be 1 byte so I read the data into a char and then cast it as a short. 我知道我正在阅读的int将始终是1个字节,所以我将数据读入一个char然后将其作为一个短片。 It got this working at some point in the past but I somehow messed it up when cleaning up my code. 它在过去的某个时刻得到了这个工作,但在清理我的代码时我以某种方式搞砸了它。

At this point the program is printing 此时程序正在打印

"The integer is 127" “整数是127”

When it should be printing 什么时候应该打印

"The integer is 1" “整数是1”

Does anybody know why this may be? 有人知道为什么会这样吗?

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> 
#include <string.h>

int main(int argc, char *argv[]){
    FILE *inp;
    char r;
    short i;

    if ((inp = fopen(argv[0],"r")) == NULL){
    printf("could not open file %s for reading\n",argv[1]);
    exit(1);}

    fread((void *)&r,(size_t) 1,(size_t) 1, inp);
    i = (short)r;

    printf("The integer is %d\n",i);        
}

You should call fread like this to read an int : 你应该像这样调用fread来读取一个int

int num;
fread(&num, sizeof(int), 1, inp);

Also, it would be wise to check the return value which, if successful in your case, should be 1: 此外,检查返回值是明智的,如果在您的情况下成功,则应为1:

#incude <errno.h>
errno = 0;
if(fread(&num, sizeof(int) 1, inp) != 1)
    strerror(errno);

Edit 编辑

If the value you're reading is only 8 bits, you should use unsigned char to read it like so: 如果您正在读取的值仅为8位,则应使用unsigned char来读取它,如下所示:

unsigned char num;
fread(&num, 1, 1, inp);

You fopen(argv[0], "r") , but report an error opening argv[1] . fopen(argv[0], "r") ,但报告错误打开argv[1] It is not normal to open your program for reading (though if the wind is blowing right and the phase of the moon is correct, you might get away with it). 打开你的阅读程序是不正常的(虽然如果风吹得正确并且月相是正确的,你可能会侥幸逃脱)。

The chances are you intended to use: 您打算使用的机率如下:

if (argc != 2)
    …report usage…
if ((inp = fopen(argv[1], "r")) == NULL)
    …report error…

Also, the } at the end of the line (as in exit(1);} ) is a very weird layout convention. 此外,行末尾的} (如exit(1);} )是一个非常奇怪的布局约定。 Personally, I loathe it. 就个人而言,我厌恶它。 Fortunately, I've only seen it on SO. 幸运的是,我只是在SO上看过它。

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

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