< c‎ | io
File input/output

File access
Direct input/output
Unformatted input/output
Formatted input
Formatted output
File positioning
Error handling
Operations on files
Defined in header <stdio.h>
size_t fwrite( const void *buffer, size_t size, size_t count,
               FILE *stream );
(until C99)
size_t fwrite( const void *restrict buffer, size_t size, size_t count,
               FILE *restrict stream );
(since C99)

Writes count of objects from the given array buffer to the output stream stream. The objects are written as if by reinterepreting each object as an array of unsigned char and calling fputc size times for each object to write those unsigned chars into stream, in order. The file position indicator for the stream is advanced by the number of characters written.


[edit] Parameters

buffer - pointer to the first object in the array to be written
size - size of each object
count - the number of the objects to be written
stream - pointer to the output stream

[edit] Return value

The number of objects written successfully, which may be less than count if an error occurs.

If size or count is zero, fwrite returns zero and performs no other action.

[edit] Example

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
enum { SIZE = 5 };
int main(void)
    double a[SIZE] = {1, 2, 3, 4, 5};
    FILE *f1 = fopen("file.bin", "wb");
    int r1 = fwrite(a, sizeof a[0], SIZE, f1);
    printf("wrote %d elements out of %d requested\n", r1,  SIZE);
    double b[SIZE];
    FILE *f2 = fopen("file.bin", "rb");
    int r2 = fread(b, sizeof b[0], SIZE, f2);
    printf("read back: ");
    for(int i = 0; i < r2; i++)
        printf("%f ", b[i]);


wrote 5 elements out of 5 requested
read back: 1.000000 2.000000 3.000000 4.000000 5.000000

[edit] References

  • C11 standard (ISO/IEC 9899:2011):
  • The fwrite function (p: 335-336)
  • C99 standard (ISO/IEC 9899:1999):
  • The fwrite function (p: 301-302)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • The fwrite function

[edit] See also

prints formatted output to stdout, a file stream or a buffer
(function) [edit]
writes a character string to a file stream
(function) [edit]
reads from a file
(function) [edit]