The function fread () in C

Function size_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream) in standard C Library reads data from the given stream into the pointed array, by ptr.

Function size_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream) in standard C Library reads data from the given stream into the pointed array, by ptr .

Declare the function fread () in C

Below is the declaration for the fread () function in C:

 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 size * nmemb bytes.

size - This is the size (byte value) of each element to be read.

nmemb - This is the number of elements, with each element having the size of byte size.

stream - This is the pointer to a FILE object that defines an Input Stream.

Returns the value

The total number of successfully read elements is returned as a size_t object, which is an integer data type. If this number is different from the nmemb parameter, then an error has occurred or End-Of-File has been encountered.

For example

The following program C illustrates the usage of the fread () function in C:

 #include #include int  main () {  FILE  * fp ; char  c [] = "Hoc C co ban va nang cao tai QTM !!!" ; char  buffer [ 100 ]; /* mo file de doc va ghi */  fp  =  fopen ( "baitapc.txt" , "w+" ); /* Ghi du lieu vao file */  fwrite ( c ,  strlen ( c ) + 1 , 1 ,  fp ); /* thiet lap vi tri con tro tim kiem ve dau file */  fseek ( fp ,  SEEK_SET , 0 ); /* Doc va hien thi du lieu */  fread ( buffer ,  strlen ( c )+ 1 , 1 ,  fp );  printf ( "%sn" ,  buffer );  fclose ( fp ); return ( 0 ); } 

Compile and run the above C program to see the results:

According to Tutorialspoint

Previous lesson: Function fopen () in C

Next lesson: Function freopen () in C

« PREV POST
READ NEXT »