How to read integer from binary using fread?

I realized that my much larger file is not working because it cannot read the first integer in the binary correctly. This is my test file that I created for this. I know that the int I'm reading will always be 1 byte, so I read the data in char and then throw it as short. At some point, this worked, but I somehow messed it up when clearing my code.

At this point, the program prints

"The integer is 127"

When should he print

"The integer is 1"

Does anyone know why this could 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);        
}
+4
source share
2 answers

fread : int:

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

, , 1:

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

Edit

, , 8 , unsigned char, :

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

fopen(argv[0], "r"), argv[1]. , (, , , ).

, :

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

, } ( exit(1);}) . . , SO.

+2

Source: https://habr.com/ru/post/1529708/


All Articles