Friday, April 24, 2009

Opening a file using constructor

Opening a file using constructor
This involves two steps
1. Create file stream subject to manage the stream using the appropriate class. That is the class ofstream is used to create the output stream and the class ifstream to create the input stream.
2. Initialize the file object with the desired filename.

Syntax:
Ofstream object(file_name);

Example:
Ofstream obj(“sample.doc”)

This creates obj1 as an ofstream that manages the output stream.
#include stream.h
#include string.h

Void main()
{
char str[]=”ssi computer center”;
ofstream outfile(“sample.doc”);
for(int j=0;j<>Syntax:
Ifstream object (file_name);

Example:

Ifstream obj(“sample.doc”)

This creates obj1 as an ifstream that manages the input stream.

#include fstream.h
void main()
{
char ch;
ifstream in(“sample.txt”);
while(!in.eof())
{
in.get(ch);
cout<< ch; } }

#include fstream.h
void main()
{
const int MAX=80;
char buffer[MAX];
ifstream infile(“sample.txt”);
while(!infile.eof())
{
infile.getline(buffer, MAX);
cout<< buffer;
}
}

No comments:

Post a Comment