Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a float from binary file in C?

Tags:

c++

c

file-io

Everything I'm finding via google is garbage... Note that I want the answer in C, however if you supplement your answer with a C++ solution as well then you get bonus points!

I just want to be able to read some floats into an array from a binary file

EDIT: Yes I know about Endian-ness... and no I don't care how it was stored.

like image 983
Polaris878 Avatar asked Sep 14 '09 17:09

Polaris878


1 Answers

How you have to read the floats from the file completely depends on how the values were saved there in the first place. One common way could be:

void writefloat(float v, FILE *f) {
  fwrite((void*)(&v), sizeof(v), 1, f);
}

float readfloat(FILE *f) {
  float v;
  fread((void*)(&v), sizeof(v), 1, f);
  return v;
}
like image 76
sth Avatar answered Oct 31 '22 12:10

sth