Hi, having some problems reading in a binary file, using the fread() command.

The function below is meant to take in a filename and header structure (structure not important) and open the file, which is a .ppm file if you are interested, then skip through the header of the file (which i believe it does) then fread all of the rest of the data in the file into one big array (width * height of ppm image). After this return the pointer (to the array where it has stored all of this data) to the function that called it....only problem is, that when i try to print out the buffer (variable - ptr_data in my code) i dont get what is in the file, and the fread only reads one item then terminates...

You should realize that it is unsafe to use the width*height values supplied in the file directly, always do some sanity checking on them before allocating memory.

06-21-2005

Giant

okay, obvious question time :S

how do i open the file in binary mode and what does fopen() do ?

06-21-2005

mitakeet

fopen(fname,"rb");

What do you mean what does fopen do? It opens the file for input or output (or both).

06-21-2005

Giant

sorry got confused about fopen and if there was a different binary variation, but got it now.

Anyway I am still getting the wrong data back, I have even gone as far as found out the total count (as fread() is meant to return total number of items read) but when the value of count is printed out it returns (EDIT)the correct amount (which for a ppm image of 492 by 708 is 1045008 [3*width*height])(EDIT)

any other ideas :/ about what could be affecting the fread line/or function as a whole?

thanks for the help,
Giant.

p.s. I used fopen(fname, "rb") and this passed the if defination on the fread line, but like i said above still getting wrong values back :_(

06-21-2005

mitakeet

Post your updated code and I will take a look. If you have some sample input, you can attatch that as well.

06-21-2005

Giant

read up abit ;) so apparently the count of fread thinks it is taking in the full amount....

06-21-2005

Giant

i have just worked out what it is doing,

it is reading in the correct hex values but as it reads more it it pushes them along the buffer so my output looks like -: 6a293870, the hex file actually goes (after header) 70 38 29 6a

when infact i need the output to be 70 (and thats it) any ideas why i am going wrong on that front ?

06-21-2005

Giant

i have just checked and it seems to be reading the file in, in 4 byte chunks per array

I think you need to post some code. Strip the problematic code out to a separate program and make it as small as you can that still replicates the problem. Be sure to include the appropriate data file!