简体   繁体   中英

How to read a float from binary file in C?

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.

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

Provided that it's written as compatible binary representation.

read for file descriptors, fread for FILE* s and istream::read for c++ iostreams. Pick whatever pleases you:

read(fd,&f,sizeof(f))==sizeof(f)

fread(&f,sizeof(f),1,fp)==1

fin.read((char*)&f,sizeof(f)).gcount()==sizeof(f)

You could use fread . (Note the the API is for C, even though the website says C++ reference :))

Use fread() from <stdio.h> . The assertions should be replaced with 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 you might run into endian issues if you transfer files between different architectures.

If the file is all "float" and you wanted to read it X number of times, all you have to do is this:

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
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 typecast your float to int32 and save , load and typecast.

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

May be wrong (I haven't used the C++ F.IO functions for a loooong loooong time)

If these values are sequentially placed into a binary file you can do a read of sizeof(float) bytes per float value into a character array. You can then cast these into a float value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM