C programming fread stdio.h


size_t fread(void * restrict ptr,
size_t sz , size_t nmemb ,
FILE * restrict stream);

Parameters:
ptr -A pointer to the storage which store the data read from the stream.

sz -Each size of the object read from the stream.

nmemb -The number of objects to be read from the stream.

stream -The file from which the object is to be read.

Return type
size_t -Returns the number of elements successfully read which is same as ‘nmemb’.If EOF or error is encountered the return value is less than ‘nmemb’.If size or ‘nmemb’ is zero,’fread’ returns zero and the contents of the array and the state of the stream remain unchanged.

In C programming the <stdio.h> fread function read ‘nmemb’ number of objects of each ‘sz'(the second parameter) size from the file ‘stream’ into the ‘ptr’ array.In calling this function the file indicator is incremented by the number of characters successfully read.If an error occurs,the resulting value of the file position indicator for the stream is indeterminate.If a partial element is read,its value is indeterminate.

Note in a system that distinguished between text mode and binary mode the file should be opened in binary mode.

Code example

FILE *fp=fopen(“text.txt” , “r”);

char str[20] ;

int count = 20 , ret ;

if (fp != NULL)
{
ret = fread(str, sizeof(char), 20 , fp);
/*… evaluate or do anything with the ‘str’ string */
}
else
 printf(“File opening failed”);

fclose(fp);

The above program reads 20 characters from the ‘text.txt’ and stores it in ‘str’ array.After running the program the ‘ret’ must be 20 else an error has occurred.





Use of fread

The main use of ‘fread’ is to read a block of objects with one single line instead of writing multiple ‘fgetc’ to read the object one by one.The above program is a good example of this case,if we were to use ‘fgetc’ we have to call it 20 times which may in fact introduce unnecessary lines of code with lesser efficiency.Another program is given below which is a slight alternation of the above program.

Code example

FILE *fp=fopen(“text.txt” , “r”)

char str[20] ;

int count = 20 , ret ;

if (fp != NULL)
{
ret = fread(str, sizeof(str) , 1 , fp);
/*… evaluate or do anything with the ‘str’ string */
}
else
 printf(“File opening failed”);

fclose(fp);

Look carefully at the ‘fread’ call,the second argument is ‘sizeof(str)'(not sizeof(char)) and the third argument is ‘1’.Since this time we would like to read an object of ‘str’ array size,the number of times to be read is just once,hence the third argument is 1.In the previous program however the size of object to be read at a time is the size of a single ‘char’ and which must be read 20 times,so 20 is the third argument.


Related links

->C fgetc stdio.h

->C fwrite stdio.h