Page 293 - DCAP404 _Object Oriented Programming
P. 293
Object-oriented Programming
Notes char ch;
myfile.get(ch);
cout << ch << endl; //the output should be ‘W’ and the pointer
will move to point ‘e’
cout << char(myfile.peek()) << endl; //should display “e”
cout << char(myfile.peek()) << endl; //should display “e” again
cout << myfile.peek() << endl; //should display 101
myfile.get(ch);
cout << ch << endl; //will display “e” again and move the
pointer to ‘l’
myfile.close();
}
putback()
This function returns the last read character, and moves the pointer back. In other words, if you
use get() to read a char and move the pointer to next character, then use putback(), it will show
you the same character, but it will set the pointer to previous character, so the next time you call
get() again, it will again show you the same character as shown in the following program.
//Program demonstrating use of putback() function
#include <fstream.h>
void main()
{
// Assume that the text contained in data.dat file is “Welcome to
C++”
ifstream myfile(“data.dat”);
char ch;
myfile.get(ch);
cout << ch << endl; //output will be ‘W’
myfile.putback(ch);
cout << ch << endl; //output will again be ‘W’
myfile.get(ch);
cout << ch << endl; // output will again be ‘W’
myfile.close();
}
flush()
I/O streams are created and maintained in the RAM. Therefore, when dealing with the output
file stream, the data is not saved in the file as the program enters them. A buffer in the memory
holds the data until the time you close the file or the buffer is full. When you close the file the
286 LOVELY PROFESSIONAL UNIVERSITY