tellp() in file handling with c++ with example

The tellp() function is used with output streams, and returns the current “put” position of the pointer in the stream. It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.

Syntax:

pos_type tellp();

Return – Current output position indicator on success otherwise  return -1.



Example 1 –

filter_none

edit
close

play_arrow

link
brightness_4
code

// cpp code to get the position at particular
// position using tellp() function
#include <iostream>
#include <fstream>
using namespace std;
  
int main()
{
    fstream file;
  
    // open file in read and write mode
    file.open("myfile.txt", ios::out);
    file << "geeksforgeeks";
  
    // print the position of the pointer in file
    cout << "the current position of pointer is :"
         << file.tellp() << endl;
  
    // close the open file
    file.close();
}

chevron_right


Output –

the current position of pointer is :-1

In the above code the tellp() returns the current position to which it point in a file.

Example 2 –

filter_none

edit
close

play_arrow

link
brightness_4
code

// code to add content at particular position 
// using tellp()
#include <fstream>
using namespace std;
  
int main()
{
    long position;
    fstream file;
  
    // open the file in read and write mode
    file.open("myfile.txt");
  
    // write content in the file
    file.write("this is an apple", 16);
    position = file.tellp();
  
    // set position of pointer usin seekp
    file.seekp(position - 7);
    file.write(" sam", 4);
    file.close();
}

chevron_right


Output –

this is a sample

Here tellp() function returns the position of pointer then using seekp() function the pointer is shift back from n position here it shift 7 position back and then insert the content at that position .

This article is contributed by Shivani Baghel . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : Vaibhav Bajpai



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.