C Library Function - fread()
Description
C Library Function **size_t fread(void ptr, size_t size, size_t nmemb, FILE stream) Reads data from the given stream stream into the array ptr pointed to by the given pointer.
Declaration
Below is the declaration of the fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
- ptr -- This is a pointer to a memory block with a minimum size of sizesize * nmemb bytes.
- size -- This is the size of each element to be read, 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 input stream.
Return Value
The total number of elements successfully read is returned as a size_t object, which is an integer data type. If the total differs from the nmemb argument, an error may have occurred or the end of the file may have been reached.
Example
The following example demonstrates the use of the fread() function.
Example
#include
#include
int
main
(
)
{
FILE
fp
;
char
c
[
]
=
"This is runoob"
;
char
buffer
[
20
]
;
/* Open the file for reading and writing */
fp
=
fopen
(
"file.txt"
,
"w+"
)
;
/* Write data to the file */
fwrite
(
c,
strlen
(
c
)
1
,
1
, fp
)
;
/* Seek to the beginning of the file */
fseek
(
fp,
0
,
SEEK_SET
)
;
/* Read and display the data */
fread
(
buffer,
strlen
(
c
)
1
,
1
, fp
)
;
printf
(
"%s\n"
, buffer
)
;
fclose
(
fp
)
;
return
(
0
)
;
}
Let us compile and run the program above, which will create a file file.txt, then write the content This is runoob. Next, we use the fseek() function to reset the write pointer to the beginning of the file; the file contents are as follows:
This is runoob
C Standard Library -