C Reading binary file with fread()

523 views Asked by At

im trying to read file from stdin with hex values:

0x0a

0x00 0x0a

0x61 0x00 0x61 0x00 0x0a

0x00 0x00 0x00

int i = 0;
unsigned char x = 0;        
            while(x != 0x0a && x != EOF){
                fread(&x, 1 , 1, stdin);
                tab[i] = x;
                i++;
            }

With this loop i'm getting segmentation fault with last line.

1

There are 1 answers

0
mtijanic On

Without seeing the declaration of tab we can't really be certain what is triggering the segfault (most likely out of bounds access to tab).

However, you shouldn't use fread with stdin - fread is for reading binary files, it will read the binary representation of every character on the screen. You are actually reading a byte representation of a character, pretty much the same as if you were doing x = getchar() or scanf("%c", &x)

So you will read "0x0a\n0x00 0x0a\n" etc.

Now, you are testing it against the value of 0x0a, which is actually a '\n', so you likely aren't reading past the first line.

What you want to be doing is:

scanf("0x%x", &x);

Which will read a single hex value, such as "0x0a", which you can then check against that constant above.

Another thing - You have declared x as an unsigned char, but are testing it against EOF, which is an int, -1. I'm surprised the compiler didn't give you a warning there. You should pretty much always read the value into an int, so I'd redeclare it as int.

Also, when reading binary files (i.e. using fread), you will never read the EOF value, since that is a valid value to be found in the file. Instead, if end of file has been reached, fread will return 0. And you can check whether it has been reached using feof(file).