I have always thought that WriteFile is more efficient than fwrite, because fwrite calls down to WriteFile internally, but the following test code show me that fwrite is faster
If properly setup, WriteFile()
can be more efficient than fwrite()
. WriteFile()
allows you to fine-tailor the conditions it uses to when performing the IO request you're issuing.
For example, you can bypass the intermediate buffered IO subsystem and pull directly from your data pointer as if it were the intermediate IO buffer, therefore removing a significant middle-man. The setup, however, is somewhat restrictive. Your data pointer must lay on a byte boundary equivalent to the sector size of the volume being written to. No such facility exists with fwrite()
for hopefully obvious reasons. Windows API enthusiasts (circa J. Richter and his brethren) are big fans of twiddling with such usages of WriteFile()
to squeeze every last drop out of their Windows program IO performance.
And if you're wondering why people aren't WriteFile()
love-children I can assure you many people are, but none of them are the least-bit interested in portable code. The ones that are (or just aren't that concerned about it (what was it Knuth said about premature optimization..?), choose standard facilities like fwrite()
.
If you're really interested in the MSVCRT-implementation of fwrite()
and how it does what it does, check out the source. It is shipped with every version of VC++ Standard or greater (perhaps not Express; I've never checked).