C fwrite()

The fwrite() function is defined in the stdio.h header file. It helps to write the data into the given specified stream from the array pointed to, by ptr.


size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); #where stream should be a file pointer

 

fwrite() Parameters: 

The fwrite() function takes four parameters. This function is mainly used for writing binary data, it is a complementary function of fread().

Parameter Description Required / Optional
ptr the pointer to the array of elements to be written Required
size the size in bytes of each element to be written Required
nmemb the number of elements, each one with a size of size bytes Required
stream the pointer to a FILE object that specifies an output stream Required

fwrite() Return Value

The return value of fwrite() function is the total number of elements successfully write. It is returned as a size_t object, which is an integral data type.

Input Return Value
successful integer value equivalent to nmemb
error or EOF a value less than nmemb

Examples of fwrite() 

Example 1: Working of fwrite() function in C?


#include <stdio.h>
#include <string.h>
int main()
{
   FILE *pnt;
   char st[] = "Welcome to C Programming";

   pnt = fopen( "myfile.txt" , "w" );
   fwrite(st , 1 , sizeof(st) , pnt );

   fclose(pnt);
  
   return(0);
}

Output:


Welcome to C Programming

Example 2: How fwrite() works in C?


#include <stdio.h>

int main (){
   FILE *pnt;
     int cnt;
     char ar[6] = "hello";
 
     pnt = fopen("mysample.txt", "wb");
     cnt = fwrite(ar, 1, 5, pnt);
     fclose(pnt);
 
     return 0;
}

Output:


/*opens a file named sample.txt, writes an array of characters(below text) to the file, and closes it. */
hello