Pages

Wednesday, December 8, 2010

Reading Binary Files

Let's try to read the files we created in previous articles using "fwrite()", function. As I told you, you can not read or open a file written using "fwrite()" by any method other than using the "fread() function. The syntax of "fread()" is similar to the "fwrite()" function. fread( ) function causes the data read from the disk to be placed in the structure variable specified within the syntax. The function "fread()" returns the number of records read. Ordinarily, this should correspond to the third argument, the number of records we asked for... 1 in this case. When there are no more records to be read means we have reached the end of file, since fread() cannot read anything, it returns a 0. By testing for this situation, we know when to stop reading.So let's see how a binary file will be read. We will be reading the same files one by one.

Example 1 : Reading the "list" file , created in example 1 in the previous post

#include
#include
struct person
{
char name[12];
int age;
};


void main()
{
clrscr();
FILE *fp;
fp=fopen("list","w");
person p;
printf("\nEnter name ");
scanf("%s",&p.name);
printf("\nEnter age ");
scanf("%d",&p.age);
fwrite(&p,sizeof(person),1,fp);
printf("\n1 person added");
fclose(fp);
// Reading starts from here
fp=fopen("list","r");
fread(&p,sizeof(person)1,fp); // reading the data using the fread() function
printf("\nHere is the data entered in the file...");
printf("\nName : %s",p.name);
printf("\nAge : %d",p.age);
fclose(fp);
}

Description
The writing part is same as given earlier. When it comes to reading the file, the "fread()" reads the data of the file(name and age) and stores it to the object "p". When we print the values of "p.name" and "p.age", it will print the data which was there in the file. How does "fread()" know how many records to read? There are two things to remember before answering this question, first - since we have written "fread()" just once, it will perform the read operation just once, and secondly "fread()" does not read records, it reads "bytes". How many bytes constitue a record has been informed to it by using the "sizeof" operator. We are telling the "fread()" function to read "sizeof" amount of bytes from the file. In this example the size of one record is 14 bytes (12 bytes for name,2 bytes for age), therefore the "fread()" function will read the first 14 bytes from the file. The first bytes will form the data of the first person.


Example 2 : Reading the "library.dat" file, created in example 2 in the previous post.
#include
#include
struct books
{
int bookno,price;
char name[12],pub[20];
};
void main()
{
clrscr();
char c;
FILE *fp;
fp=fopen("library.dat","a");
books b;
do
{
printf("\nBook no ");
scanf("%d",&b.bookno);
fflush(stdin);
printf("\nEnter book name ");
gets(b.name);
printf("\nEnter publisher ");
gets(b.pub);
printf("\nEnter book price ");
scanf("%d",&b.price);
fwrite(&b,sizeof(books),1,fp);
fflush(stdin);
printf("\nNew book added to library.");
printf("\nPress Y to add more books, N to Close : ");
scanf("%c",&c);
}while(c=='Y' || c=='y');
fclose(fp);
fp=fopen("library.dat","r");
while(fread(&b,sizeof(books),1,fp)==1) // reading book data one record at a time
{
printf("\nBook no %d",b.bookno);
printf("\nBook name %s",b.name);
printf("\nPublisher %s",b.pub);
printf("\nPrice %d",b.price);
printf("\n-----------------------------------"); // Just a seperator, two differntiate between 2 records optional)
}
fclose(fp);
}

Description
Since there are multiple records in this file and we don't know how many records have been entered by the user, we'll to put the "fread()" function inside a while loop. Remember that fread returns 1 if it finds data in the file and 0 if there is no data to be read, therefore we have written the condition "while(fread)==1", so that the loop continues to read the data till the end of the file. When all the data has been read, the "fread()" function will return 0 and the loop will terminate. All the records are printed by one by one with an optional seperator between each record.


Example 3 - Reading the "school" file, created in example 3 in the previous post.

#include
#include
struct student
{
int rollno,marks1,marks2,marks3,total,avg;
char name[10];
};
void main()
{
student s;
FILE *fptr;
fptr=fopen("school","a");
char ch;
int i;
for(i=0;i<5;i++)
{
printf("\nRollno ");
scanf("%s",&s.rollno);
printf("\nName ");
scanf("%s",&s.name);
printf("\nMarks 1 ");
scanf("%d",&s.marks1);
printf("\nMarks 2 ");
scanf("%d",&s.marks2);
printf("\nMarks 3 ");
scanf("%d",&s.marks3);
s.total=s.marks1+s.marks2+s.marks3;
s.avg=s.total/3;
fwrite(&s,sizeof(student),1,fptr);
printf("\nSaved in the file");
}
fclose(fptr);
fptr=fopen("school","r");
while(fread(&s,sizeof(student),1,fptr)==1)
{
printf("\nRollno %d",s.rollno);
printf("\nName %s",s.name);
printf("\nMarks 1 %d",s.marks1);
printf("\nMarks 2 %d",s.marks2);
printf("\nMarks 3 %d",s.marks3);
printf("\nTotal marks %d",s.total);
printf("\nAverage %d",s.avg);
printf("\nPress any key to continue ...");
getch();
}
fclose(fp);
}


Description
The reading process is same as that of example 2. Here we have added an "Press any key" message also so that the user can pause the screen after each record.

0 comments:

Post a Comment