Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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. 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"

When it should be printing

"The integer is 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);        
}
like image 280
user3081405 Avatar asked Mar 03 '14 00:03

user3081405


People also ask

Which function is used to read binary data from a file?

The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor.

Which methods are used to write and read into from a binary file?

The RandomAccessFile class implements both the DataInput and DataOutput interfaces. To read and write from a random-access file, use methods such as readInt/writeInt and readChar/writeChar that we discussed in the preceding section.


2 Answers

You should call fread like this to read an 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:

#include <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:

unsigned char num;
fread(&num, 1, 1, inp);
like image 84
Fiddling Bits Avatar answered Nov 07 '22 20:11

Fiddling Bits


You fopen(argv[0], "r"), but report an error opening 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. Personally, I loathe it. Fortunately, I've only seen it on SO.

like image 29
Jonathan Leffler Avatar answered Nov 07 '22 20:11

Jonathan Leffler