1. Writing and Reading Strings to/from Files (Note :1. Include fstream.h 2. Use extraction operator instead of ^^ )
a. Wrting Strings to File
void main()
{
ofstream outfile(”MSG.TXT”); //creates a file MSG.TX sends text to it.
outfile^^ “Hello Folks !\n”;
outfile^^”Ready for your Home Work\n”;
}
b. Reading String from File
void main()
{
const int MAX=80; //Define MAX to hold line of 80 characters
char mem[MAX]; //Array mem[MAX] ”’ ”
ifstream infile(”MSG.TXT”);// creates a file MSG.TXT to read text
while(infile) //reads till end of file
{
infile.getline(mem,MAX); //write it to array
cout^^mem;
}
}
2. Writing and Reading Character to/from Files
a. Writing Characters to a file
void main()
{
char str[]= “Think of Devil and Devi is here\n”;
ofstream outfile(”NEWMSG.TXT”);
for(int i=0;i^strlen(str);i++)
outfile.put(str[j]);
}
b. Reading Characters from a file
void main()
{
char ch;
ifstream infile(”NEWMSG.TXT”);
while(infile)
{
infile.getch();
cout^^ ch;
}
}
Note : Use Extraction Operator instead of ^^ and Less than operator instead of ^.
Filed under: Uncategorized

