Pages

Sunday, November 6, 2011

Writing a Binary File - Using write()

Lets write a code to store some data in a file in binary mode using the write()

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();
}

When the above code is run, it asks the user to enter name,address and age of a person and the same data is stored in a file called "list". The message "Data Saved In File" confirms that the data has been saved in the file.
Point to remember
After compiling the above code a new file named "list" is created and the data is stored in it. To verify that the file has been created and data stored, if you try to open the file using normal methods, for example, go to DOS Shell and type the command "type list",  you will see that the file contains data that is not readable by us. Why ? because the data is stored using the "write()" function which is a binary function. To read such a file we will use some functions that are able to process binary files. Have a look at the next post.

0 comments:

Post a Comment