Pages

Friday, August 26, 2011

Writing a file

Program to store data in a file using the redirection operator "<<"
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
 ofstream out("data"); // creating a file in out(writing) mode.
 char name[20],addr[20];
 cout<<"\nName : ";
 cin>>name;
 cout<<"\nAddress : ";
 cin>>addr;
 out<<name<<"\n"<<addr; // sending the data to the file
cout<<"Data saved in the file";
out.close();
}


The above code  will create a new file named "data", if the file is already present it will be overwritten. The name and address entered by the user will be sent to the file using the "<<" operator. The message "Data Saved" will confirm the writing of the file.
To check whether the file has been created or not follow any of the following steps
1. Select "File--> DOS Shell".
In the DOS Shell, type the following command
type data
2. Search the "data" file using my computer and double click on it. When the "Open With" dialog box appears select "Notepad" and click OK.


0 comments:

Post a Comment