C Library Functions -fwrite()

C Standard Library - <stdio.h>

Description

C Library Functionssize_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)holdptrWrites the data in the array pointed to by ptr to the given stream.streamIn.

Declaration

The following is the declaration of the fwrite() function.

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

Parameter

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

Return Value

If successful, the function returns a size_t object representing the total number of elements, which is an integer data type. If this number differs from the nmemb parameter, an error will be displayed.

Example

The following example demonstrates the usage of the fwrite() function.

Example

#include<stdio.h> int main () { FILE *fp; char str[] = "This is example.com"; fp = fopen( "file.txt" , "w" ); fwrite(str, sizeof(str) , 1, fp ); fclose(fp); return(0); }

Let us compile and run the above program, which will create a filefile.txt, whose contents are as follows:

This is example.com

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

Example

#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>

other extensions