Latest web development tutorials

C library functions - fwrite ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionssize_t fwrite (const void * ptr, size_t size, size_t nmemb, FILE * stream) writes the data pointed to by ptrarray to a given streamstream.

statement

Here is the fwrite () function's declaration.

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

parameter

  • ptr - This is a pointer to be written element of the array.
  • size - the size of which is to be written for each element, in bytes.
  • nmemb - This is the number of elements, the size of each element is size bytes.
  • stream - This is a pointer to a FILE object, the FILE object specifies an output stream.

return value

If successful, the function returns a size_t object that represents the total number of elements, when the object is an integer data type. If this number nmemb parameters are different, an error is displayed.

Examples

The following example demonstrates the fwrite () function is used.

#include<stdio.h>

int main ()
{
   FILE *fp;
   char str[] = "This is w3cschool.cc";

   fp = fopen( "file.txt" , "w" );
   fwrite(str , 1 , sizeof(str) , fp );

   fclose(fp);
  
   return(0);
}

Let's compile and run the above program, which will create a filefile.txt, which reads as follows:

This is w3cschool.cc

Now let's use the following procedure to view the contents of the above file:

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}

C standard library - <stdio.h> C standard library - <stdio.h>