I have the following block to test the behaviours of the seekg and tellg when I try to get a file size:
int size = 0;
ifstream in(fileName.c_str(), ifstream::in | ifstream::binary);
if(in)
{
in.seekg(0,ifstream::end);
size = in.tellg();
cout << endl;
cout << endl;
cout << "********** size stream1*** =" << size << endl;
in.seekg(0,ios::end);
size = in.tellg();
cout << "********** size stream2*** =" << size << endl;
in.seekg(0,ios::end);
size = in.tellg();
cout << "********** size stream3*** =" << size << endl;
in.seekg(100,ios::end);
size = in.tellg();
cout << "********** size stream4*** =" << size << endl;
in.seekg(0,ios::beg);
size = in.tellg();
cout << "********** size stream5*** =" << size << endl;
in.seekg(100);
in.seekg(0, ios::end);
size = in.tellg();
cout << "********** size stream6*** =" << size << endl;
in.seekg(100);
in.seekg(0, ios::cur);
size = in.tellg();
cout << "********** size stream7*** =" << size << endl;
in.seekg(-100,ios::end);
size = in.tellg();
cout << "********** size stream8*** =" << size << endl;
in.seekg(ios::beg,ios::end);
size = in.tellg();
cout << "********** size stream9*** =" << size << endl;
in.seekg(ios::beg);
in.seekg(ios::end);
size = in.tellg();
cout << "********** size stream10*** =" << size << endl;
cout << endl;
cout << endl;
}
Its results are followed:
********** size stream1*** =1846
********** size stream2*** =1846
********** size stream3*** =1846
********** size stream4*** =1946
********** size stream5*** =0
********** size stream6*** =1846
********** size stream7*** =100
********** size stream8*** =1746
********** size stream9*** =1846
********** size stream10*** =2
My questions are the following:
OK, here we go:
tellg()
will yield the position object useful to get back to the position you are at. The type returned is a std::streampos
which is std::fpos<std::mbstate_t>
. However, an std::fpos<std::mbstate_t>
converts to a std::streamoff
which is an integer. Essentially, a std::streampos
converts to the number of characters from the first position to the current position.0
characters relative to std::ios_base::beg
clearly sets the position to the start of the file. Did you mean to use std::ios_base::cur
?seekg()
will be relative to the start, current position, or the end depending on the whence parameter being std::ios_base::beg
, std::ios_base::cur
, or std::ios_base::end
.std::ios_base::seekdir
type is an enumeration and std::ios_base::end
probably has the value 2
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With