Sunday, August 23, 2009

READING AND WRITING CLASS OBJECTS FROM/TO FILES

#include
#include
class invt
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void);
};

void invt :: readdata(void)
{
printf("Enter Name: "); scanf("%s",&name);
printf("Enter Code: "); scanf("%d",&code);
printf("Enter Cost: "); scanf("%f",&cost);
}
void invt :: writedata(void)
{
printf("%s\t%d\t%f\n",name,code,cost);
}
void main()
{
clrscr();
invt item[3];
fstream file;
file.open("stock.dat",ios::in|ios::out);
printf("Enter the details for three items\n");
for(int i=0;i<3;i++)
{
item[i].readdata();
file.write((char *) &item[i],sizeof(item[i]));
}
file.seekg(0);
printf("\n\t\tOUTPUT\n\n");
printf("Name\tCode\tCost\n");
for(i=0;i<3;i++)
{
file.read((char *) &item[i],sizeof(item[i]));
item[i].writedata();
}
file.close();
getch();
}

OUTPUT:
In the above program object is directly written in to the file but not the elements or the data directly and the data is retrieved by means of the object but not directly.

Enter details for three items
Enter Name: aaaa
Enter Code: 333
Enter Cost: 45
Enter Name: bbbb
Enter Code: 434
Enter Cost: 54
Enter Name: cccc
Enter Code: 535
Enter Cost: 65

OUTPUT

Name Code Cost
aaaa 333 45
bbbb 434 54
cccc 535 65

WRITING NUMBERS IN TO FILE

#include"fstream.h"
#include"conio.h"
void main()
{
Clrscr();
float ht1[4],ht[4]={13,14,54,66};
fstream file;
file.open("aaa.a",ios::out);
file.write((char *) &ht,sizeof(ht));
file.close();
file.open("aaa.a",ios::in);
file.read((char *) &ht1,sizeof(ht1));
for(int i=0;i<4;i++)
{
printf("%f",ht1[i]);
printf("\n");
}
file.close();
getch();
}

OUTPUT:
The numbers in the floating point array ht are first converted into character type and then they are stored in the file with the file name “aaa.a” and then they are retrieved from the file with file name “aaa.a” and stored in the array of floating point ht1 and these values are printed as follows.

13
14
54
66