Read binary files in C (fread Matlab)

0

In Matlab I have a binary file read like this:

fid = fopen('nombrearcihvo', 'r', 'ieee-le')

the contents are short floating, or 32 bits (4 bytes) and to read the first element I use the following:

fread(fid, 1, 'float32')

And throws me 0.6721

But I need to read it in a code in C, and I used the following code

float v;
ifile = fopen(namefileI,"r");
fread((void*)(&v), sizeof(v), 1, ifile);

To see the result I do it by sending the content of v to another file of the form:

fwrite ((void*)(&v), sizeof(v), 1, fp);

And throws these symbols at me: ± ,?

Actually, I have tried several ways, with none that has left me somewhat satisfied since the result does not seem to match the one thrown by Matlab.

My pc is Little-Endian, so I should be reading the same, and the float32 type is the same as 4 bytes of C ....

What code or steps should I take to convert the data in the file and get the same result as in Matlab?

Thanks!

    
asked by Romina C. M. 06.11.2017 в 18:34
source

1 answer

2

The way you are using the functions is correct. That is, the type of the arguments as the sizes are according to what you need. The problem is not in the use of fopen() , fread() or fwrite() .

Something that must be clear is that the function fwrite will not know the type of data that is made to point. That is the intention to have a void * as an argument. The function expects an initial address and a size to make a raw write (byte by byte) element by element.

By your description you expect fwrite to do the floating point conversion to characters to be read later in a text file. That will not happen with 'fwrite ()'. That's why instead, when you open that file, you only see unexpected characters:

  

±,?

When you open this file, they will be displayed on the screen based on the corresponding UTF-8 character:

  • ? in UTF-8 (hex) it is 0x3F
  • , in UTF-8 (hex) is 0x2C
  • '' (space) in UTF-8 (hex) is 0x20
  • ± in UTF-8 (hex) is 0xC2B1

Assuming that this is the order in which the characters appear, now, if we concatenate all these data, it gives us the following:

0x3F2C20C2B1

If we take the most significant 32 bits:

0x3F2C20C2

and if we decoficate the value based on the IEEE-754 standard we will obtain:

0.67237484

Which is not exactly 0.6721 but is in the range. If we use the same tool to obtain the hexadecimal representation of 0.6721 we get:

0x3f2c0ebf

We can notice here that the first two characters correspond. Something to consider, and based on the comment made by @eferion is that the accuracy of the data type float is 6 digits. The error we see here could be due to a conversion error in the figures shown.

    
answered by 07.11.2017 в 05:58