Introduction:
The tellp function retrieves the current position of the "put" pointer within the stream for output streams. This function does not require any parameters and returns a value of the pos_type member type, which is an integer data type indicating the current position of the put stream pointer.
Syntax:
pos_typetellp();
Return -
If the operation is successful, it will return the current output position indicator; if not, it will return -1.
Example:1
// utilizing the tellp() function, write some C++ code to find the position at a specific location.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
// reading and writing a file
file.open("file.txt", ios::out);
file << "javaCppTutorial";
// print the file's pointer position
cout<< "the current position of pointer is :"
<<file.tellp() <<endl;
// close the open file
file.close();
}
Output:
the current position of pointer is :10
Explanation:
In the provided code snippet, the tellp function retrieves the current position within the file associated with the icpp tutorials.
Example 2 -
// code to add content using tellp() at a specific spot
#include <fstream>
using namespace std;
int main()
{
long position;
fstream file;
// open the file in read and write mode
file.open("myfile.txt");
// Fill out the file with content
file.write("this is an apple", 16);
position = file.tellp();
//set the pointer's position with seekp
file.seekp(position - 7);
file.write(" sam", 4);
file.close();
}
Output:
this is a sample
Explanation:
In this scenario, the tellp function provides the current pointer position. Subsequently, the pointer is repositioned 7 positions back using the seekp method, allowing content to be inserted at that location.