fwrite(Buffer, sizeof(A), N, fp) vs fwrite(Buffer, sizeof(A) * N, 1, fp)

I have a byte array which stores a lot of struct data.

When I use fwrite function, which is more efficient way?

// POD
struct Foo
{
}

Foo Buffer[128];
...

1. fwrite( (void*)Buffer, sizeof(Foo), 128, fp );
2. fwrite( (void*)Buffer, sizeof(Foo) * 128, 1, fp);

I don't think it makes any difference on most compilers/platforms.
You can look at the assembly of the 2 statements to see if there is any difference.
@jonnin

Thanks!
You'd need to do some timings to actual see in practice - but my gut feel is that one write would be better than 128 writes.

But why not simply:

 
fwrite((void*)Buffer, sizeof(Buffer), 1, fp);

https://linux.die.net/man/3/fwrite
On success, fread() and fwrite() return the number of items read or written.


> 1. fwrite( (void*)Buffer, sizeof(Foo), 128, fp );
The result is a number between 0 and 128, depending on how many records were written.
A record is written completely, or not at all.

> 2. fwrite( (void*)Buffer, sizeof(Foo) * 128, 1, fp);
This runs the risk of having a partially complete record at the end of the file.

but, for 2), you would get 0 result instead of 1, so you can still trap an error, though less precisely if that happened.

if foo or the number of foos is very large, you can also tamper with its buffer to tweak at it but this may not be optimal for all target machines so that is aggravating. If it is not too large, it won't matter, most likely.
Last edited on
fwrite() returns the number of items actually written. If you write 128 items but only say 60 were written correctly - what state is the file actually in given that this is actually an array being written? What about the 60 already written? If you only write as one object then you either have a successful write or you don't - either it's all been written OK or it hasn't.
If you only write as one object then you either have a successful write or you don't - either it's all been written OK or it hasn't.

I don't think that's true. According to https://cplusplus.com/reference/cstdio/fwrite/ :
Internally, the function interprets the block pointed by ptr as if it was an array of (size*count) elements of type unsigned char, and writes them sequentially to stream as if fputc was called for each byte.
(emphasis added).

So the return value is yes/no, but that doesn't mean the write completely sucessful vs. nothing written. I always call fwrite with size=1 and count=(number of bytes to write). That way I know if there was a partial write and do something about it if necessary.
Registered users can post here. Sign in or register to post.