3

I want to read/write C float values from a binary file if it was created in C?

The file was created like this:

#include <stdio.h>

int main() {
    const int NUMBEROFTESTELEMENTS = 10;
    /* Create the file */
    float x = 1.1;
    FILE *fh = fopen ("file.bin", "wb");
    if (fh != NULL) {
       for (int i = 0; i < NUMBEROFTESTELEMENTS; ++i)
       {
            x = 1.1*i;
            fwrite (&x,1, sizeof (x), fh);
            printf("%f\n", x);
       }
        fclose (fh);
    }

    return 0;
}

I found a method like this:

file=open("array.bin","rb")
number=list(file.read(3))
print (number)
file.close()

But this won't guarantee to me the read value was a C float.

gabor aron
  • 390
  • 2
  • 3
  • 15
  • What is in `array.bin`? – Abdul Niyas P M Oct 28 '21 at 10:09
  • @AbdulNiyasPM I updated the question with the code which generates the file. – gabor aron Oct 28 '21 at 10:14
  • Does this answer your question? [Reading 32 bit signed ieee 754 floating points from a binary file with python?](https://stackoverflow.com/questions/6286033/reading-32-bit-signed-ieee-754-floating-points-from-a-binary-file-with-python) – mch Oct 28 '21 at 10:17
  • @mch maybe, I don't know how this returns me the exact values, can you give me an example based on this, then I can accept it as an answer too. – gabor aron Oct 28 '21 at 10:35

2 Answers2

3
import struct
with open("array.bin","rb") as file:
    numbers = struct.unpack('f'*10, file.read(4*10))
print (numbers)

This should do the job. numbers is a tuple of the 10 values.

mch
  • 9,424
  • 2
  • 28
  • 42
1

If you do care about performance, I would suggest using numpy.fromfile for float values reading:

import numpy as np

class FloatReader:
    def __init__(self, filename):
        self.f = open(filename, "rb")
    
    def read_floats(self, count : int):
        return np.fromfile(self.f, dtype=np.float32, count=count, sep='')

This approach is much faster than struct.unpack in terms of performance!

Anatoly
  • 5,119
  • 1
  • 14
  • 8