How to write default structure values multiple times using fwrite()

c++

I want to write a default structure, N times, to a file, using fwrite.

typedef struct foo_s {

 uint32 A;
 uint32 B;
 char desc[100];

}foo_t;

void init_file(FILE *fp, int N)
{
   foo_t foo_struct = {0};
   foo_struct.A = -1;
   foo_struct.B =  1;

   fwrite(&foo_struct, sizeof(foo_struct), N, fp);    }

The above code does not write foo_struct N times to the file stream fp.

Instead it writes N*sizeof(foo_struct) bytes starting from &foo_struct to fp.

Can anyone tell how to achieve the same with a single fwrite?

Best Solution

You can't with a single fwrite(). You'd have to use a loop:

int i;
for (i = 0; i < N; ++i)
    fwrite(&foo_struct, sizeof(foo_struct), 1, fp);

The third parameter of fwrite() is the number of objects to write, not the number of times to write a single object.

Related Question