Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - fread()

C Library Function - fread()

C Standard Library - <stdio.h> C Standard Library -

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

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 - <stdio.h> C Standard Library -