C programming fwrite stdio.h


size_t fwrite(const void * restrict ptr,
size_t sz , size_t nmemb ,
FILE * restrict stream);

Parameters:
ptr -A pointer to the storage which store the data to be written to the file.

sz -Each size of the object read from the storage.

nmemb -The number of objects to be written to the file.

stream -The file to which the data is written.

Return type
size_t -Returns the number of elements successfully written, which will be less than ‘nmemb’ only if a write error is encountered.If size or ‘nmemb’ is zero,’fwrite’ returns zero and the state of the stream remains unchanged.

In C programming the <stdio.h> fwrite function write ‘nmemb’ data of size ‘sz’ from the storage pointed by the string ‘ptr’ to the file ‘fp’.After the call to ‘fwrite’ the file indicator is advanced by the number of characters successfully written.If an error occurs,the resulting value of the file position indicator for the stream is indeterminate.

Note on systems that distinguish between text and binary file access modes, the file should be opened in binary mode.

Code example

FILE *fp=fopen(“dat.bin” , “wb”) , *fp1;

char str[]=”Á e îIkh/ÿÿÆh3{Â^bÅ’ ” , ch[40];

int ret ;

if (fp != NULL)
{
ret = fwrite(str , sizeof(str), 1 , fp); //write the ‘str’ string to dat.bin
printf(“ret=%d” , ret);
}
else
 printf(“File opening failed”);

fclose(fp);

fp1=fopen(“dat.bin” , “wb”) ;

fread( ch , sizeof(str) , 1 , fp1 );

printf(“\nch=%s” , ch);

fclose(fp1);

Output,

ret=1
ch=Á e îIkh/ÿÿÆh3{Â^bÅ’

Now open the dat.bin file you will see the string “Á e îIkh/ÿÿÆh3{Â^bÅ’ “,note the string consists of an unsigned character and so some characters may appear differently in the file.

Link : Differences and uses : Signed and unsigned char type





Use of ‘fwrite’

The main use of ‘fwrite’ is to write a block of data to the file without needing to call ‘fputc‘ multiple times.Thus ‘fwrite’ provides a more efficient way of writing the data to the file.In the above program we have used ‘fwrite’ to write the data to the file instead of using ‘fputc’ to write character one by one.

P.S. prefer ‘fwrite’ over ‘fputc’ to write data to the file.


Related links

->C fputc stdio.h

->C fread stdio.h