Page 290 - DCAP404 _Object Oriented Programming
P. 290
Unit 13: Working with Files
Some useful File Operation Functions Notes
In addition to the function discussed thus far, there are many more functions which come handy
in writing practical programs on data file processing. An assorted list of them is given below:
tellg()
This function returns an int type value representing the current position of the pointer inside the
data file opened in input mode as demonstrated in the following program.
//Program demonstrating tellg() function
#include <fstream.h>
void main()
{
//Assume that the text stored in data.dat file is “Welcome to C++”
ifstream myfile(“data.dat”);
char ch;
for(int j=0; j<4;j++)
myfile.get(ch);
cout <<myfile.tellg() << endl;
//this should return 5, as four characters have been read from the
file so the current pointer points at next
//character, i.e., 5th characterHello is 5 characters long
myfile.close();
}
tellp()
This function does to output files what tellg() does to input files. It returns an int type value
representing the current position of the pointer inside the data file opened in output mode as
shown in the following code snippet.
ofstream myfile(“data.dat”);
myfile<<“India”;
cout << myfile.tellp();
//this should return 6, as five characters have been written in the
file so the current pointer points at next
//position, i.e., 6th
myfile.close();
seekg()
While reading data from a file this function is used to shift the pointer to a specified location as
shown in the following code snippet.
//Assume that the text stored in data.dat file is “Welcome to C++”
ifstream myfile(“data.dat”);
char ch;
LOVELY PROFESSIONAL UNIVERSITY 283