How to read a float from binary file in C?

2019-01-19 04:39发布

问题:

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.

回答1:

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;
}


回答2:

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)


回答3:

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



回答4:

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.



回答5:

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


回答6:

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)



回答7:

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.



标签: c++ c file-io