How to read a float from binary file in C?

前端 未结 7 738
挽巷
挽巷 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:55

    Use fread() from . The assertions should be replaced with actual error handling code.

    #include 
    #include 
    
    #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.

提交回复
热议问题