The tellg method is implemented within the isstream class for working with input streams. This function is responsible for providing the current position of the "get" pointer within the stream. It does not require any arguments and produces an output of the pos_type data type, which signifies the current position of the get stream pointer.
Syntax:-
pos_typetellg();
Returns:
If the request is successful, the current position of the gecpp tutorialer will be displayed; if unsuccessful, pos_type(-1) will be returned.
Let's consider a few examples to grasp the functionality of the tellg function in C++.
Example:1
// C++ program to show the tellg() method in action.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "JavaCppTutorial";
istringstream in(str);
string word;
in >> word;
cout<< "After reading the word \"" << word
<< "\" tellg() returns " <<in.tellg() << '\n';
}
Output:
After reading the word "JavaCppTutorial" tellg() returns -1
Example:2
// C++ program to show the tellg() method in action.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "welcome, JTP";
istringstream in(str);
string word;
in >> word;
cout<< "After reading the word \"" << word
<< "\" tellg() returns " <<in.tellg() << '\n';
}
Output:
After reading the word "welcome," tellg() returns 8.
Example:3
#include <iostream>
#include <fstream>
int main () {
std::ifstream is ("JTP.txt", std::ifstream::binary);
if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
is.read (buffer,length);
is.close();
std::cout.write (buffer,length);
delete[] buffer;
}
return 0;
}
Explanation:
The software is designed to read the "JTP.txt" document and display its contents on the console, assuming it exists in the program's current directory and contains accurate information.
You have the option to compile and execute the program on your local system for testing purposes. Ensure that the "JTP.txt" file is present and holds the necessary data. Subsequently, the application should display this data on the console.
Properties:-
The tellg function does not provide information on the file size or the byte offset from the beginning. Instead, it returns a token value that can be stored and later used to seek to the same position within the file.