Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Ashishprajapati29.wordpress.

com

FILE POINTERS IN C++


(FILE MANIPULATORS)
In C++ we have a get pointer and a put pointer for getting (i.e. reading)
data from a file and putting (i.e. writing) data on the file respectively.

 seekg():-
seekg() is used to move the get pointer to a desired location with respect to
a reference point.
Syntax: file_pointer.seekg (number of bytes ,Reference point);
Example: fin.seekg(10,ios::beg);

 tellg():-
tellg() is used to know where the get pointer is in a file.
Syntax: file_pointer.tellg();
Example: int posn = fin.tellg();

 seekp():-
seekp() is used to move the put pointer to a desired location with respect to
a reference point.
Syntax: file_pointer.seekp(number of bytes ,Reference point);
Example: fout.seekp(10,ios::beg);

 tellp():-
tellp() is used to know where the put pointer is in a file.
Syntax: file_pointer.tellp();
Example: int posn=fout.tellp();

1|Page
Ashishprajapati29.wordpress.com

The reference points are:


ios::beg – from beginning of file
ios::end – from end of file
ios::cur – from current position in the file.

In seekg() and seekp() if we put – sign in front of number of bytes then we


can move backwards.

Program:
#include<iostream>

#include<fstream>

using namespace std;

int main()

fstream fout;

char buf[200];

fout.open("file1.txt",ios::trunc | ios::out);

char ch[100];

cout<<"Enter data into file = ";

cin.getline(ch,20,'#');

fout<<ch;

int pos;

pos = fout.tellp();/*..........................................*///////tellp

cout<<"Current position of pointer = "<<pos;

fout.seekp(3,ios::beg); /*..........................................*///////seekp
//////seekp

fout<<"nkok";

2|Page
Ashishprajapati29.wordpress.com

cout<<"\nIndex location = "<<fout.tellg()<<endl;/*.........................*///////tellg

fout.close();

fout.open("file1.txt", ios :: in | ios :: ate);

cout << "\nReading from the file ... " << endl;

fout.seekg(3); /*..........................................*///////seekg

while (!fout.eof()) {

fout.getline(buf, 100);

cout << buf << endl;

Output:

3|Page

You might also like