Search code examples
ciofwrite

Writing array of structs to binary file using fwrite


I have:

pointfile = fopen("points.bin", "wb");
void    savepoints(point points[], int n, FILE f){
    fwrite(&points, sizeof(point), n, &f);
    return;
}
fclose(pointfile);

where typedef struct {float x; float y;} point;

and called by savepoints(buffer, npoints, *pointfile);

But nothing is written to the file. Can anyone spot my mistake? I can't see how to go about this, and other's I find searching either don't relate, or have merely got me this far.


Solution

  • Need to pass a FILE * as parameter like:

    test.c

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct 
    {
      float x,
            y;
    }point;
    
    /* function to save points data to myfile */
    void save_points(point *points, int num_points, FILE *myfile)
    {
      /* have to use points not (&points) here */
      fwrite(points, sizeof(point), num_points, myfile);
    }
    
    int main()
    {
      FILE *pointfile;
      point *points; int num_points, index;
      pointfile = fopen("points.txt", "w");
      if(!pointfile)
      {
        fprintf(stderr, "failed to create file 'points.txt'\n");
        goto err0;
      }
      num_points = 10;
      points = malloc(num_points * sizeof(point));
      if(!points)
      {
        fprintf(stderr, "failed to alloc `points`\n");
        goto err1;
      }
      /* points are uninitialized but can still write uninitialized memory to file to test.. */
      save_points(points, num_points, pointfile);
      free(points);
      fclose(pointfile);
      return 0;
    
    err1:
      fclose(pointfile);
    err0:
      return 0;
    }
    

    Results

    $ ./test
    $ ls -l points.txt 
    -rw-r--r-- 1 me me 80 Dec 14 22:24 points.txt