Name
fwrite - Writes to the output stream.
Syntax
#include <stdio.h>
size_t fwrite(buffer, size, count, stream)
const void *buffer;
size_t size;
size_t count;
FILE *stream;
Description
The fwrite function writes up to count items of length size
from buffer to the output stream. The file pointer
associated with stream (if there is one) is incremented by
the number of bytes actually written.
If stream is opened in text mode, each carriage return is
replaced with a carriage-return/line-feed (CR-LF) pair. The
replacement has no effect on the return value.
Return Value
The fwrite function returns the number of full items
actually written, which may be less than count if an error
occurs. Also, if an error occurs, the file-position
indicator cannot be determined.
See Also
fread(DOS), write(DOS)
Example
#include <stdio.h>
FILE *stream; long list[100]; int numread; int numwritten;
main()
{
/* File opened in "binary" mode: */
if ((stream = fopen("data.bin", "w+b")) != NULL) {
/* Write 100 long integers to "stream": */
numwritten = fwrite((char
*)list,sizeof(long),100,stream);
printf( "Wrote %d items\n", numwritten );
}
else
printf("Problem opening the file");
fclose(stream);
if ((stream = fopen("data.bin", "r+b")) != NULL) {
/* Attempt to read in 100 long ints: */
numread = fread((char
*)list,sizeof(long),100,stream);
printf("Number of items read = %d\n",
numread);
}
else
printf("Was not able to open the file\n");
}
This program opens a file named data.bin and writes 100 long
integers to the file. The program then tries to open
data.bin and read in 100 long integers. If the attempt
succeeds, the program displays the number of actual items
read.
(printed 6/18/89)