CKTIS / C
fwrite — C23 stream function
`fwrite(ptr, size, nmemb, stream)` from `<stdio.h>` writes up to `nmemb` objects of `size` bytes from the array designated by `ptr` to a stream. Each object is processed as successive `fputc` calls over its `unsigned char` representation; the function returns the number of complete objects written.
Version: C23
Syntax
size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);fwrite(ptr, size, nmemb, stream) from <stdio.h> writes up to nmemb objects of size bytes from the array designated by ptr to a stream. Each object is processed as successive fputc calls over its unsigned char representation; the function returns the number of complete objects written.
The example writes three int values with fwrite(values, sizeof values[0], 3, stream), which returns 3. It rewinds and reads them back using the same type, then prints 3 7 -2 42, demonstrating that the return count is in elements, not bytes.
A result below nmemb means a write error; also inspect ferror, because bytes from a partial final object may already have been written. If size or nmemb is zero, the result is zero and the stream state is unchanged. The source must cover size * nmemb bytes. Raw object representations can contain padding and depend on endianness and type widths, so they are not a portable interchange format.
Examples
#include <stdio.h>
int main(void){int values[3]={7,-2,42},copy[3]={0};FILE *stream=tmpfile();if(!stream)return 1;size_t written=fwrite(values,sizeof values[0],3,stream);rewind(stream);if(fread(copy,sizeof copy[0],3,stream)!=3){fclose(stream);return 1;}printf("%zu %d %d %d\n",written,copy[0],copy[1],copy[2]);return fclose(stream)==0?0:1;}
Result
3 7 -2 42
The example writes three `int` values with `fwrite(values, sizeof values[0], 3, stream)`, which returns `3`. It rewinds and reads them back using the same type, then prints `3 7 -2 42`, demonstrating that the return count is in elements, not bytes.