简体   繁体   中英

C Reading binary file with fread()

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.

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 (ie 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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