2

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.

5
  • 4
    should pass in a FILE * to savepoints Commented Dec 14, 2013 at 10:20
  • does it make a difference, since I had ...*pointfile and ...&f? Commented Dec 14, 2013 at 10:24
  • 1
    Shouldn't it be fwrite(points instead of fwrite(&points? Commented Dec 14, 2013 at 10:26
  • @OllieFord Pass FILE* as suggested. FILE can be copied, but because it contains things like the current stream position, you may run into unexpected issues if you copy it, write using that file, then use the original copy outside of savepoints. Commented Dec 14, 2013 at 10:39
  • 1
    actually it does matter since &f != pointfile Commented Dec 14, 2013 at 10:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.