mercredi 1 novembre 2017

Why seekg doesn't work on stringstream passed by reference?

I need to get (i)stringstream/ifstream size. I use the code on more places so I wrote a function for it. The function takes istream& as a parameter (so it is more general). The code uses seekg to the end of the stream and looks like this:

#include <iostream>
#include <sstream>
#include <fstream>

std::streamsize getStreamSize(std::istream& is) {
    const std::streampos currentPos{ is.tellg() };
    const std::streamsize size{ is.seekg(0, std::ios::end).tellg().seekpos() };
    is.seekg(currentPos);

    return size;
};

int main()
{
    using namespace std;
    string s{ "some string" };
    cout << "string: " << s << endl;

    istringstream ss{ s };

    istream& is{ ss };
    streampos size{ is.seekg(0, ios::end).tellg() };
    cout << "stream size: " << size << endl;

    cout << "stream size reference: " << getStreamSize(is) << endl;

    cout << "stream size reference: " << getStreamSize(ss) << endl;


    ifstream ifs{ "some_file_path.txt" };
    cout << "file stream size: " << getStreamSize(ifs) << endl;

    return 0;
}

And the output of this code is following:

string: some string
stream size: 11
stream size reference: 0
stream size reference: 0
file stream size: 6021120

Why it is not possible to get (i)stringstream size passed by reference, but it is possible to get i(stringstream) size of local reference or ifstream passed by reference?

Windows 10, SDK version 10.0.16299.0, Visual Studio Community 15.4.2

Aucun commentaire:

Enregistrer un commentaire