Reputation: 41613
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.
Upvotes: 9
Views: 32753
Reputation: 374
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
Upvotes: 2
Reputation: 169833
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.
Upvotes: 3
Reputation: 143329
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)
Upvotes: 5
Reputation: 9174
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)
Upvotes: 1
Reputation: 229934
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;
}
Upvotes: 20
Reputation: 2661
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.
Upvotes: 0