Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdio.h>
size_t fwrite(const void * __restrict__buffer, size_t size, size_t count, FILE * __restrict__stream);
#define _OPEN_SYS_UNLOCKED_EXT 1
#include <stdio.h>
size_t fwrite_unlocked(const void * __restrict__buffer, size_t size,
size_t count, FILE * __restrict__stream);
Writes up to count items of size size from the location pointed to by buffer to the stream pointed to by stream.
When you are using fwrite() for record I/O output, set size to 1 and count to the length of the record to be written. You can only write one record at a time when you are using record I/O. Any string longer than the record length is truncated at the record length. A flush or reposition is required before a subsequent read.
When you are using fwrite() for blocked I/O output, set size to 1 and count to the length of the block to be written. You can only write one block at a time when you are using blocked I/O. Any string longer than the block length is truncated at the block length.
Because fwrite() may buffer output before writing it out to the stream, data from prior fwrite() calls may be lost where a subsequent call to fwrite() causes a failure when the buffer is written to the stream.
fwrite() has the same restriction as any write operation for a read immediately following a write or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must also be an intervening flush or reposition unless an EOF has been reached.
fwrite_unlocked() is functionally equivalent to fwrite() with the exception that it is not thread-safe. This function can safely be used in a multithreaded application if and only if it is called while the invoking thread owns the (FILE*) object, as is the case after a successful call to either the flockfile() or ftrylockfile() function.
fwrite() returns the number of items that were successfully written.
This number can be smaller than count only if a write error occurred.
⁄* CELEBF51
This example writes NUM long integers to a stream in binary
format.
It checks that the &fopen. function is successful and that
100 items are written to the stream.
*⁄
#include <stdio.h>
#define NUM 100
int main(void)
{
FILE *stream;
long list[NUM];
int numwritten, number;
if((stream = fopen("myfile.dat", "w+b")) != NULL )
{
for (number = 0; number < NUM; ++number)
list[number] = number;
numwritten = fwrite(list, sizeof(long), NUM, stream);
printf("number of long characters written is %d\n",numwritten);
}
else
printf("fopen error\n");
}