Page 289 - DCAP404 _Object Oriented Programming
P. 289
Object-oriented Programming
Notes ifstream filename(“c:\cppio.dat”);
char ch;
while(!filename.eof())
{
filename.get(ch);
cout << ch;
}
filename.close();
}
Did u know? What do you need to declare to store the date read?
You need to declare a character array to store the data read when reading from a file. The
character array can be any size as long as it is big enough to store what you are reading in.
The general procedure of writing one character at atime in a file is listed below:
1. Create an output file stream from <fstream.h> header file:
ofstream name_of_output_stream;
2. Open the data file by passing the file name (optionally full name) to this output stream:
name_of_output_stream.open(“data.dat”);
Both the above statements can be combined in the following:
ofstream name_of_output_stream(“data.dat”);
3. Write a character in the opened file using << operator:
name_of_output_stream << ‘A’;
4. When finished close the file using close() function:
name_of_output_stream.close();
The ofstream class is defined in fstream.h header file. Therefore you must include this file in
your program. The complete program is listed below.
//Writing a character in a data file
#include <fstream.h>
int main()
{
ofstream filename(“data.dat”);
filename << ‘A’;
filename.close();
return 0;
}
282 LOVELY PROFESSIONAL UNIVERSITY