The fread
library function in C is used to read values from a given data stream and put them values into an array.
In order to use fread
, the stdio.h
library needs to be included in the program, as shown:
#include <stdio.h>
The fread
function takes in the following 4 parameters:
ptr − points to a block of memory that is at least size
len bytes long.
len − number of elements that need to be read, where each element is size bytes long.
size − size of each element (in bytes) that needs to be read.
input − points to a FILE object that determines a stream of input. This is shown below:
size_t fread(void *ptr, size_t size, size_t len, FILE *input)
If all the elements are read successfully, the total number of read elements is returned as a size_t object
. In case the End Of File was reached, or there was an error, the value returned will be different from the len
parameter that was passed when fread
was called.
In the example below, we declare a new FILE object named newfile and write “Welcome to Educative!” using fwrite
. With the help of fopen
, we open the file for reading and writing. strlen
can then be used to calculate the value of len. We can determine the starting point of the file using fseek
, and read data from it into the array pointed to by ptr
. Once all the read/write operations are complete, we can close the file using fclose
. This is shown below:
#include <stdio.h>#include <string.h>int main () {FILE *input;char message[] = "Welcome to Educative!";char ptr [50];int len = strlen(message)+1;// since one character is 1 byte long, the size of each// element that needs to be read is 1int size = 1;// Opening file for reading and writinginput = fopen("myfile.txt", "w+");fwrite(message, len, 1, input);// Determining the starting point of the filefseek(input, 0, SEEK_SET);// Reading data from file to ptrfread(ptr, len, size, input);printf("%s\n", ptr);fclose(input);return(0);}
Free Resources