Mano-Wii
Mano-Wii

Reputation: 592

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?

Upvotes: 1

Views: 2466

Answers (1)

Tam&#225;s Zahola
Tam&#225;s Zahola

Reputation: 9311

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.

Upvotes: 3

Related Questions