C Library Function - fwrite()
Description
C Library Function **size_t fwrite(const void ptr, size_t size, size_t nmemb, FILE stream) Puts the ptr Write the data in the array pointed to by to the given stream stream it.
Declaration
Below is the declaration of 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 with 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; this object is an integer data type. If this number differs from the nmemb argument, an error has occurred.
Example
The following example demonstrates the use of the fwrite() function.
Example
#include
<
stdio.h
int
main
(
)
{
FILE
fp;
char
str
[
]
=
"
This is runoob.com
"
;
fp
=
fopen
(
"
file.txt
"
,
"
w
"
)
;
fwrite
(
str
,
sizeof
(
str
)
,
1
,
fp
)
;
fclose
(
fp
)
;
return
(
0
)
;
}
Let us compile and run the program above, which will create a file file.txt, with the following content:
This is runoob.com
Now let us use the following program to view the content of the file above:
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 -