How to read and write an array of double values to and from a binary file in C

2 Answers

0 votes
#include <stdio.h>

#define SIZE 5

int main(void)
{
    const char* filename = "d:\\date.bin";
    double arr1[SIZE] = {1.1, 2.23, 3.333, 4.4444, 5.55555};

    FILE* fp = fopen(filename, "wb");
    fwrite(arr1, sizeof(double), SIZE, fp);
    fclose(fp);

    double arr2[SIZE] = {0};
    fp = fopen(filename, "rb");
    fread(arr2, sizeof(double), SIZE, fp);

    for (int i = 0; i < SIZE; i++)
        printf("%lf\n", arr2[i]);

    fclose(fp);
}




/*
run:

1.100000
2.230000
3.333000
4.444400
5.555550

*/

 



answered Feb 3, 2023 by avibootz
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]) { 3.14, 8.7, 1.382, 0.04 }, sizeof(double), SIZE, fp);
    assert(rc == SIZE);
    fclose(fp);

    fp = fopen("d:\\data.bin", "rb");
    double arr[SIZE] = { 0.0 };
    rc = fread(&arr, sizeof arr, SIZE, fp);
    for (int i = 0; i < SIZE; i++) {
        printf("%.3f\n", arr[i]);
    }
    fclose(fp);

    return 0;
}



/*
run:

3.140
8.700
1.382
0.040

*/

 



answered Apr 20, 2024 by avibootz

Related questions

1 answer 165 views
1 answer 169 views
2 answers 233 views
2 answers 260 views
1 answer 149 views
...