fwrite

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 in the given array buffer to the output stream stream. Objects are not interpreted in any way.

Parameters

buffer - pointer to the first object 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

Return value

The number of objects written successfully.

Example

fwrite with error checking.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    // write buffer to file
    FILE *f1;
    char buffer[] = { 'x' , 'y' , 'z' };
    f1 = fopen("file.bin", "wb");
    int ret_code = fwrite(buffer, sizeof(char), sizeof(buffer), f1);
    if (ret_code < (int)sizeof(buffer))
       if (ferror(f1))
       {
          perror("fwrite()");
          fprintf(stderr,"fwrite() failed in file %s at line # %d\n", __FILE__,__LINE__-5);
          exit(EXIT_FAILURE);
       }
    fclose(f1);
 
    // read the same data and print it to the standard output
    FILE *f2;
    char rbuf[10];
    f2 = fopen("file.bin", "rb");
    const char* res = fgets(rbuf, sizeof(rbuf), f2);
    fclose(f2);
 
    if (res) { // points to rbuf on read success, NULL on failure
        puts(res);
    }
 
    return EXIT_SUCCESS;
}

Output:

xyz

References

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

See also

prints formatted output to stdout, a file stream or a buffer
(function)
writes a character string to a file stream
(function)
reads from a file
(function)
C++ documentation for fwrite
doc_C_Language
2016-10-10 18:35:22
Comments
Leave a Comment

Please login to continue.