Page 288 - DCAP404 _Object Oriented Programming
P. 288
Unit 13: Working with Files
Self Assessment Notes
Fill in the blanks:
6. In case the file has been successfully attached to the stream the pointer is placed at the
………………… position.
7. Care should be taken to ensure that the program does not ……………………. a file
unintentionally.
8. …………………… files are unformatted and uninterpreted file of binary digits.
9. Function that provides the number of symbols read - ………………………. .
13.3 Reading/Writing a Character from/into a File
Reading and writing a character in a data file has been dealt with in the previous sections in
detail. The general procedure of reading a file one character at a time is listed below:
1. Create an input file stream from <fstream.h> header file:
ifstream name_of_input_stream;
2. Open the data file by passing the file name (optionally full name) to this input stream:
name_of_input_stream.open(“data.dat”);
Both the above statements can be combined in the following:
ifstream name_of_input_stream(“data.dat”);
3. Set up a character type variable to hold the read character.
char ch;
4. Read a character from the opened file using get() function:
name_of_input_stream.get(ch);
This way you can read the entire file in a loop stopping condition of the loop being the end
of file:
while(!filename.eof())
{
name_of_input_stream.get(ch);
//process the read character
}
5. When finished close the file using close() function:
name_of_input_stream.close();
The if stream class is defined in fstream.h header file. Therefore you must include this file
in your program. The complete program is listed below.
//reading a file one character at a time
#include <fstream.h>
void main() //the program starts here
{
LOVELY PROFESSIONAL UNIVERSITY 281