codescracker


c

C fread()



« Previous Function Next Function »


fread()

The fread() function reads count number of objects, each object being size bytes in length, from the stream pointed to by stream and stores them in the array pointed to by buf. The file position indicator is advanced by the number of characters read.

fread() Syntax

#include<stdio.h>
size_t fread(void *buf, size_t size, size_t count, FILE *stream);

The fread() function returns the number of items actually read.

fread() Example

Following c program writes five floating-point numbers from the bal array to a disk file called DEMO and then reads them back:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	FILE *fp;
	float bal[5]= {2.1F, 3.2F, 4.3F, 5.4F, 6.5F};
	int i;
	
	/* write values to the file */
	
	fp=fopen("demo", "wb");
	if(fp==NULL)
	{
		printf("Error in opening the file..!!\n");
		printf("Press any key to exit..\n");
		getch();
		exit(1);
	}
	if(fwrite(bal, sizeof(float), 5, fp)!=5)
	{
		printf("Error in reading the file..!!\n");
		printf("Press any key to exit..\n");
		getch();
		exit(2);
	}
	fclose(fp);
	
	/* read values from the file */
	
	fp=fopen("demo" "rb");
	if(fp==NULL)
	{
		printf("Error in opening the file..!!\n");
		printf("Press any key to exit..\n");
		getch();
		exit(3);
	}
	if(fread(bal, sizeof(float), 5, fp) != 5)
	{
		if(feof(fp))
		{
			printf("Premature end of file.");
		}
		else
		{
			printf("Error in reading the file..!!\n");
		}
	}
	fclose(fp);
	for(i=0; i<5; i++)
	{
		printf("%f ", bal[i]);
	}
	getch();
}

« Previous Function Next Function »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test