A file that has been created using binary functions like "fwrite" can only be read using the "fread" function that can read or process a binary file. Following is the same code that was given in the previous post "Writing a binary file - Using write()". If you look at the end of the code you will see that there some additional statements there.
Example 1#include "iostream.h"
#include "fstream.h"
#include "conio.h"
class person
{
char name[10],addr[20];
int age;
public:
void getpers()
{
cout<<"\nEnter name : ";
cin>>name;
cout<<"\nEnter address : ";
cin>>addr;
cout<<"\nEnter age : ";
cin>>age;
}
void showpers()
{
cout<<"\Name : "<<name;
cout<<"\nAddress : "<<addr;
cout<<"\nAge : "<<age;
}
};
void main()
{
clrscr();
person pers;
pers.getpers();
ofstream out("list",ios::app);
out.write((char *)&pers,sizeof(person));
cout<<"\nData Saved In File ";
out.close();// closing the file from write mode
// READING SECTION
ifstream in("list"); // reopening the file in read mode
in.read((char *)&pers,sizeof(person)); // reading the data using the read() function
pers.showpers(); // displaying the data
in.close(); //closing the file again
}
The above code first opens the file in the write() mode, gets the data from the user, stores into the file and then reopens the file to read the data. When the data is read using the read() function, the data will be displayed exactly as it as entered. Therefore keep in mind "if written using write(), use read()"
0 comments:
Post a Comment