Hello

I am having some trouble with something.
As I read the contents of a file into an ifstream object I occassionally want to dump all its contents into a stringstream to analyse it. Example below.

The problem I am having is that if I use ifstream.rdbuf() to dumpt the contents into a stringstream, the cursore is moved to the end of the ifstream. How can I do this without moving the cursor in the ifstream?

int main()
{

ifstream filestream;
filestream.open("file.txt", ios::out | ios::binary);

char *reads = new char;

stringstream stringstrm;

while (filestream.read(reads,1))
{
    if (*reads == 'x')
    {

    stringstrm << filestream.rdbuf(); 
    // this works but I have a problem with it.
    //The problem is that it moves the cursor in 
    //filestream to the end of filestream.
    //what I want is to have the contents of **filestream**
    //to be dumbed into **stringstrm** and the cursor to
    //filestream to be undisturbed. So when I come out of
    //the 'if' statement I can continue on where I left off
    //when 'x' was found. filstream.rdbuf() doesn't seem to
    //let me do this?


    }


}


}

You can use the tellg and seekg functions to re-establish the cursor (get pointer). As so:

std::streampos p = filestream.tellg();
stringstrm << filestream.rdbuf(); 
filestream.seekg(p);

Perfect. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.