tags:

views:

711

answers:

2

Hi

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.

Thanks

Aman Jain

+2  A: 

The only way to do this with a single fwrite is to replicate the foo_struct N times in RAM, then do a single fwrite of all that RAM.

I doubt that doing a malloc, N copies, and then an fwrite would be quicker than just doing N fwrites (this is the only reason I can think of for wanting to do this!), but if you really care, you should try it.

Airsource Ltd
+6  A: 

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.

Ferruccio