fwrite() — Write Items
Format
#include <stdio.h>
size_t fwrite(const void *buffer, size_t size, size_t count,
FILE *stream);
Language Level
ANSI
Threadsafe
Yes
Description
The fwrite()
function
writes up to count items, each of size bytes
in length, from buffer to the output stream.
Return Value
The fwrite()
function
returns the number of full items successfully written, which can be
fewer than count if an error occurs.
When using fwrite()
for
record output, set size to 1 and count to
the length of the record to obtain the number of bytes written. You
can only write one record at a time when using record I/O.
The value of errno can be set to:
- Value
- Meaning
- ECONVERT
- A conversion error occurred.
- ENOTWRITE
- The file is not open for write operations.
- EPAD
- Padding occurred on a write operation.
- EPUTANDGET
- An illegal write operation occurred after a read operation.
- ESTDERR
stderr
cannot be opened.- ESTDIN
stdin
cannot be opened.- ESTDOUT
stdout
cannot be opened.- ETRUNC
- Truncation occurred on I/O operation.
- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
Example
This example writes NUM long integers
to a stream in binary format.
#include <stdio.h>
#define NUM 100
int main(void)
{
FILE *stream;
long list[NUM];
int numwritten;
int i;
stream = fopen("MYLIB/MYFILE", "w+b");
/* assign values to list[] */
for (i=0; i<=NUM; i++)
list[i]=i;
numwritten = fwrite(list, sizeof(long), NUM, stream);
printf("Number of items successfully written = %d\n", numwritten);
}