How to read the first values from binary file in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main(void)
{
    enum { SIZE = 4 };
    
    FILE* fp = fopen("d:\\data.bin", "wb");
    assert(fp);
    
    size_t rc = fwrite((double[SIZE]) { 1.382, 3.14, 8.7, 0.04 }, sizeof(double), SIZE, fp);
    assert(rc == SIZE);
    fclose(fp);

    fp = fopen("d:\\data.bin", "rb");
    double d;
    rc = fread(&d, sizeof d, 1, fp); // read the first double
    assert(rc == 1);
    printf("First value in the file: %.3f\n", d);
    fclose(fp);

    return 0;
}



/*
run:

First value in the file: 1.382

*/

 



answered Apr 20, 2024 by avibootz

Related questions

1 answer 150 views
1 answer 381 views
1 answer 172 views
1 answer 170 views
2 answers 288 views
288 views asked Dec 30, 2020 by avibootz
1 answer 266 views
...