views:

454

answers:

2

I want to write to a std::stringstream without any transformation of, say line endings.

I have the following code:

void decrypt(std::istream& input, std::ostream& output)
{
    while (input.good())
    {
        char c = input.get()
        c ^= mask;
        output.put(c);

        if (output.bad())
        {
            throw std::runtime_error("Output to stream failed.");
        }
    }
}

The following code works like a charm:

std::ifstream input("foo.enc", std::ios::binary);
std::ofstream output("foo.txt", std::ios::binary);
decrypt(input, output);

If I use a the following code, I run into the std::runtime_error where output is in error state.

std::ifstream input("foo.enc", std::ios::binary);
std::stringstream output(std::ios::binary);
decrypt(input, output);

If I remove the std::ios::binary the decrypt function completes without error, but I end up with CR,CR,LF as line endings.

I am using VS2008 and have not yet tested the code on gcc. Is this the way it supposed to behave or is MS's implementation of std::stringstream broken?

Any ideas how I can get the contents into a std::stringstream in the proper format? I tried putting the contents into a std::string and then using write() and it also had the same result.

+4  A: 

AFAIK, the binary flag only applies to fstream, and stringstream never does linefeed conversion, so it is at most useless here.

Moreover, the flags passed to stringstream's ctor should contain in, out or both. In your case, out is necessary (or better yet, use an ostringstream) otherwise, the stream is in not in output mode, which is why writing to it fails.

stringstream ctor's "mode" parameter has a default value of in|out, which explains why things are working properly when you don't pass any argument.

Éric Malenfant
The `output.bad()` was resolved by using `std::stringstream output(std::stringstream::in|std::stringstream::out|std::stringstream::binary);`And `std::ios::binary` did nothing. The error was that an other piece of code that wrote contents to file (for debugging) was not using `std::ios::binary`.
Sean Farrell
A: 

Try to use

std::stringstream output(std::stringstream::out|std::stringstream::binary);
Miollnyr