How to read a float from binary file in C?

前端 未结 7 716
挽巷
挽巷 2020-12-10 17:31

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++ solutio

相关标签:
7条回答
  • 2020-12-10 17:51
    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)
    
    0 讨论(0)
  • 2020-12-10 17:53

    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
    
    0 讨论(0)
  • 2020-12-10 17:54
    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)

    0 讨论(0)
  • 2020-12-10 17:55

    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.

    0 讨论(0)
  • 2020-12-10 17:57

    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.

    0 讨论(0)
  • 2020-12-10 17:59

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

    0 讨论(0)
提交回复
热议问题