How to read a float from a binary file in C?

All I find through google is garbage ... Please note that I need an answer in C , however, if you add your answer using a C ++ solution as well , then you get bonus points!

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

EDIT: Yes, I know about Andians ... and no, I don't care how it was saved.

+6
c ++ c file-io
source share
7 answers

How you should read the floats from the file depends entirely on how these values ​​were stored there in the first place. One common way:

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; } 
+18
source share
 float f; if(read(fd,&f,sizeof(f))==sizeof(f)) printf("%f\n",f); else printf("oops\n"); 

Provided that it is written as a compatible binary representation.

read for file descriptors, fread for FILE* and istream::read for c++ iostreams. Choose whatever you like:

 read(fd,&f,sizeof(f))==sizeof(f) fread(&f,sizeof(f),1,fp)==1 fin.read((char*)&f,sizeof(f)).gcount()==sizeof(f) 
+5
source share

You can use fread . (Note that the API is for C, although the site says a link to C ++ :))

+3
source share

Use fread() from <stdio.h> . Assertions should be replaced with the actual error handling code.

 #include <stdio.h> #include <assert.h> #define countof(ARRAY) (sizeof (ARRAY) / sizeof *(ARRAY)) float data[5]; FILE *file = fopen("foo.bin", "rb"); assert(file); size_t n = fread(data, sizeof(float), countof(data), file); assert(n == countof(data)); 

Keep in mind that when transferring files between different architectures, you may run into problems related to Endian.

+2
source share

If the file all β€œfloats” and you want to read it X times, all you need to do is the following:

 FILE *fp; if((fp=fopen("filename.whatever", "rb"))==NULL) return 0; fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); float *f = (float *)malloc(sizeof(float)*size); if(f==NULL) { fclose(fp); return 0; } if(fread(f, sizeof(float), size, fp)!=size) { fclose(fp); return 0; } fclose(fp); // do something with f 
+2
source share
 FILE *thisFile=fopen("filename","fb"); float myFloat; fscanf(thisFile,"%f",&myFloat); fclose(thisFile); 

This works if the data is written using fprintf (implementation specific)
However, you can also output your float in int32 and save, load and type.

 std::fstream thisFile; thisFile.open("filename",ios::read|ios::binary); float myFloat; thisFile>>myFloat; thisFile.close(); 

Perhaps you are mistaken (I did not use CIO C.IO functions for loooong loooong time)

+1
source share

If these values ​​are sequentially placed in a binary file, you can read the sizeof (float) bytes for each float value in the character array. You can then translate them into a float value.

0
source share

All Articles