C Library Function - fwrite()
C Standard Library - <stdio.h>
Description
The C library function sizet fwrite(const void *ptr, sizet size, size_t nmemb, FILE *stream) writes the data from the array pointed to by ptr into the given stream stream.
Declaration
Here is the declaration for the fwrite() function.
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
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 one with a size of size bytes.
stream -- This is a pointer to a FILE object that specifies an output stream.
Return Value
On success, the function returns a size_t object, which is the total number of elements successfully written, which is an integer data type. If this number differs from the nmemb parameter, it indicates an error.
Example
The following example demonstrates the use of the fwrite() function.
#include<stdio.h>
int main ()
{
FILE *fp;
char str[] = "This is tutorialpro.org";
fp = fopen( "file.txt" , "w" );
fwrite(str, sizeof(str) , 1, fp );
fclose(fp);
return(0);
}
Let's compile and run the above program, which will create a file file.txt with the following content:
This is tutorialpro.org
Now, let's use the following program to view the content 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);
}