Search code examples
cfwritestdio

Is it good practice to use `fwrite` within loops?


I need to write an array whose parts are scattered in code.

In short, my code is this:

(...)
FILE *f = fopen(filepath, "wb"); // wb -write binary

for (uint i = 0; i < num_points; i++) {
    fwrite(points[i].loc, sizeof(float[3]), 1, f);
}

fclose(f);

As you can see, my solution was writing each new part of the array in front of the file.

But does this have a problem with efficiency, or memory reading? Should I allocate the entire array in RAM and then write the file?


Solution

  • fwrite will buffer your data until its buffer is full, or fflush/fclose/etc. is called. So it won't perform a syscall each iteration.