In C++, tellg() tells you where the next read will start. It returns the position as a number of characters from the start, so the first character is position 0.
Together with seekg() it lets you bookmark a place, jump away, and come back. It is also the usual way to find the size of a file. Include <iostream> to use it.
This is a member function of std::istream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call tellg on an input stream. It takes no arguments.
C++
std::streampos here = in.tellg(); // bookmark
// ... read more ...
in.seekg(here); // go back
Call
What it does
in.tellg()
Returns the current read position.
in.seekg(0, std::ios::end); in.tellg()
The position of the end, which is the total size.
in.seekg(here)
Goes back to a position saved earlier.
The result has the type std::streampos. You can print it, compare it, and pass it back to seekg().
Library declarations
C++
pos_type tellg();
Parameters
Parameter
Description
None
tellg() takes no parameters.
Return Value
Return Value
Description
std::streampos
The current read position, counted from the start.
-1
Returned when the stream has failed. In code, this is pos_type(-1).
C++ Examples
Example 1 — See the Position Move
Check the position before and after reading a word.
seekg(0, std::ios::end) moves the read position to the end of the data.
The end is after the seventh character, so tellg() returns 7.
For a real file, use an ifstream in the same way and the result is the size in bytes.
Example 3 — Save a Position and Come Back
Remember a position, read ahead, then return and read the same text again.
C++
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream in("one two three");
std::string a, b;
in >> a;
std::streampos mark = in.tellg();
in >> b;
std::cout << "ahead: " << b << '\n';
in.seekg(mark);
in >> b;
std::cout << "again: " << b << '\n';
return 0;
}
Output
ahead: two
again: two
How It Works
After reading one, tellg() gives the position 3, which is saved in mark.
The next read gets two and the position moves on.
seekg(mark) returns to position 3, so the second read gets two again.
Frequently Asked Questions
The current read position of an input stream as a std::streampos, counted in characters from the start. It returns -1 when the stream has failed.
Open an ifstream, call seekg(0, std::ios::end), and then tellg(). The result is the file size in bytes. Use seekg(0) afterwards to read from the start.
The stream is in a failed state. For example, a read hit the end and set failbit. Call clear() first.
tellg gives the read (get) position, tellp gives the write (put) position. An fstream keeps both.
Yes. A std::streampos can be printed with cout. Convert it with static_cast<long long> if you need a plain number.