[英]std::stringstream and std::ios::binary
I want to write to a std::stringstream
without any transformation of, say line endings. 我想写一个std::stringstream
而不进行任何转换,比如行结尾。
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::runtime_error
,其中输出处于错误状态。
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. 如果我删除了std::ios::binary
则decrypt函数完成且没有错误,但我最终得到CR,CR,LF作为行结尾。
I am using VS2008 and have not yet tested the code on gcc. 我正在使用VS2008并且尚未在gcc上测试代码。 Is this the way it supposed to behave or is MS's implementation of std::stringstream
broken? 这是它应该表现的方式还是MS的std::stringstream
的实现被破坏了?
Any ideas how I can get the contents into a std::stringstream
in the proper format? 有什么想法我怎么能以适当的格式将内容导入std::stringstream
? I tried putting the contents into a std::string
and then using write()
and it also had the same result. 我尝试将内容放入std::string
然后使用write()
,它也有相同的结果。
AFAIK, the binary
flag only applies to fstream
, and stringstream
never does linefeed conversion, so it is at most useless here. AFAIK, binary
标志仅适用于fstream
,而stringstream
永远不会进行换行转换,所以在这里它至多无用。
Moreover, the flags passed to stringstream
's ctor should contain in
, out
or both. 而且,传递给stringstream
的ctor的标志应该包含in
, out
或者两者。 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. 在你的情况下, out
是必要的(或者更好的是,使用ostringstream
)否则,流不处于输出模式,这就是写入它失败的原因。
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. stringstream
ctor的“mode”参数的默认值为in|out
,这解释了当你没有传递任何参数时,事情正常工作的原因。
尝试使用
std::stringstream output(std::stringstream::out|std::stringstream::binary);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.