I want to copy the contents of one file to the other.
Initially I thought that fgetc()
would be better than fread()
as the program won't need to reiterate through the buffer just to copy each character.
But I soon realize that repeatedly using fgetc()
is equivalent of doing multiple function calls (stack pointer) so that way it will make the process more time consuming in case of large files.
Which is more efficient?
size_t _Cdecl fread(void *__ptr, size_t __size, size_t __n,
FILE *__stream);
vs
int _Cdecl fgetc(FILE *__stream);
The problem with fgetc
is that modern C implementations support threads. A FILE
can be shared by several threads and that is why accesses to the buffer will need explicit locking. While you can enlarge the buffer by using setbuf
, it does not eliminate the need for locking. Therefore a fread
call will be almost always more performant than multiple fgetc
calls.
Any setbuf
setting can only do so much to performance. To read a single character at a time from a buffered stream you can use the POSIX standard flockfile
/funlockfile
and getc_unlocked
when the file is locked for your thread.
But even then, fread
is very likely more performant than multiple getc_unlocked
calls, because it has been optimized to read a block.