Skip to content
Related Articles

Related Articles

Difference between tellg and tellp in C++

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 23 Mar, 2021
View Discussion
Improve Article
Save Article

In this article, we will discuss the functionality of basic_istream<>::tellg and basic_ostream<>::tellp and the difference between them.

tellg(): The function is defined in the istream class, and used with input streams. It returns the position of the current character in the input stream.

Syntax:

pos_type tellg(); 

Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”.

Program 1:

Below is the C++ program to illustrate the use of tellg():

C++




// C++ program to illustrate the
// use of tellg()
#include <fstream>
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    ifstream fin;
    char ch;
  
    // Opens the existing file
    fin.open("gfg.text");
  
    int pos;
    pos = fin.tellg();
    cout << pos;
  
    fin >> ch;
    pos = fin.tellg();
    cout << pos;
  
    fin >> ch;
    pos = fin.tellg();
    cout << pos;
  
    return 0;
}


Input File:

 gfg.text
 
 hello students

Output:

tellp(): The function is defined in the ostream class, and used with output streams. It returns the position of the current character in the output stream where the character can be placed.

Syntax:

pos_type tellp();

Return Type: If the pointer points to a valid position, then this function returns the current position of the get pointer. Otherwise, it returns “-1”.

Program 2:

Below is the C++ program illustrating the use of tellp():

C++




// C++ program illustrating the
// use of tellp()
#include <fstream>
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    ofstream fout;
    char ch;
  
    // Opening the already existing file
    fout.open("gfg.text", ios::app);
    int pos;
    pos = fout.tellp();
    cout << pos;
  
    fout << "print it";
    pos = fin.tellp();
    cout << pos;
    fout.close();
  
    return 0;
}


Input File:

gfg.text

hello students
print it 

Output:

Tabular Difference between tellp() and tellg():

tellp() tellg()
This function is used with output streams and returns the current “put” position of the pointer in the stream. The function is used with input streams and returns the current “get” position of the pointer in the stream.
Syntax: pos_type tellp(); Syntax: pos_type tellg();
It returns the position of the current character in the output stream. It returns the position of the current character in the input stream.
tellp() gives the position of the put pointer. tellg() gives the position of the get pointer.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!