Files: The Tellg and Tellp Function, Write and Read Functions, Close Function

Get unlimited access to the best preparation resource for CBSE/Class-7 Science: fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 252K)

Table shows Function for Manipulation for File Pointer

Table Shows Function for Manipulation for File Pointer

The Tellg () and Tellp () Function

The tellg () function gives the position of get pointer in terms of number of bytes. Similarly, tellp () function gives the position of put pointer in terms of bytes.

Example 2

If stream in file.

In file. open (“ABC”, ios: ate).

int B = in file. tellg ().

On execution of the above statements, the input pointer is moved to the end of the file and B gives the number of bytes in the file.

Write () and Read () Functions

The functions write () and read () have two parameters: address of the variable, size of the variable. The address of the variable must be cast to the type char*. The general format is:

In file. read((char*) & v, size of v).

Out file. write((char*) & v, size of v).

Where v is the variable.

Close () Function

The file should be closed at the end if it is opened either through constructor or open () function. The General format is stream _object. Close ().

The following example works with class object and does the following operations:

  • Create a data file

  • Display a data file

  • Adding a new record

  • Modify the existing record

Example 3

# include <fstream.h>

class student


char name [30].

int run.


void get data ().

void put data ().


void student: get data ()


cout << “Enter student name”.

cin >> name.

cout << “Enter roll number”.

cin >> run.


void student: put data ()


cout << “Student name” << name << “\n”.

cout << “Student roll number” << run << “\n”.


void main ()


fstream file.

file. open (“ABC”, ios: in l ios: out l ios: binary).

student st.

/ / create a data file

int i, n.

cout << “How many records to enter”.

cin >> n.

for (i = 1; i < = n, i ++)


st. get data ().

file. Write ((char*) & st, size of st).


/ / Display a data file

file. See kg (0, ios: beg).

while (file. read ((char*) & st, size of st))


st. put data ().


file. clear ( ) / / To make the end of file mark false

/ / To append record

st. get data ().

file. write ((char*) & st, size of st).

/ / To modify a record

file. clear ( );

cout << “Enter record number”.

cin >> n.

file. See kp ((n - 1) * size of st, ios: beg).

st. get data ().

file. write ((char*) & st, size of st).

/ / To close a file

file. close ( );

Developed by: