“覆盖”时的 Stringstream write() 问题
目前,我有一个名为 Data
的字符串流。我正在通过使用以下方式查找字符串流的开头:
Data.seekp(0, std::ios::beg);
然后,我尝试将 2 个整数写入字符串流的前 8 个字节(以前,前 8 个字节设置为 0)
Data.write(reinterpret_cast<char*>(&dataLength),sizeof(int));
Data.write(reinterpret_cast<char*>(&dataFlags),sizeof(int));
使用 Visual C++ 调试器以及当我设置断点时,我可以看到 dataLength
等于 12,而 dataFlags
等于 0,因此应该分别写入 12 和 0。
写完2个整数后,好像没有什么效果。然后,我使用以下代码打印字符串流数据:
char* b = const_cast<char*>(Data.str().c_str());
for (int i = 0; i < dataLength; i++)
{
printf("%02X ",(unsigned char)b[i]);
}
我可以看到数据的前 8 个字节仍然是 0,即使我只是用两个整数覆盖了前 12 个字节(其中第一个整数!= 0)。
为什么我的字符串流中的数据没有被正确覆盖?
Currently, I have a stringstream called Data
. I am seeking to the beginning of the stringstream by using:
Data.seekp(0, std::ios::beg);
Then, I try writing 2 integers to the first 8 bytes of the stringstream (previously, the first 8 bytes were set to 0)
Data.write(reinterpret_cast<char*>(&dataLength),sizeof(int));
Data.write(reinterpret_cast<char*>(&dataFlags),sizeof(int));
Using the Visual C++ debugger and when I set a breakpoint, I can see that dataLength
is equal to 12, and dataFlags
is equal to 0, so therefore it should be writing 12 and 0 respectively.
After writing the 2 integers, it seemed to have no effect. I then print my stringstream data using the following code:
char* b = const_cast<char*>(Data.str().c_str());
for (int i = 0; i < dataLength; i++)
{
printf("%02X ",(unsigned char)b[i]);
}
I can see that the first 8 bytes of my data are still 0's even though I just overwrote the first 12 bytes with two integers (where the first integer != 0).
Why isn't the data in my stringstream being overwritten properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Data.str()是一个临时的,在该语句结束时被销毁;该临时文件的 c_str() 值只能在临时文件处于活动状态时使用(并且您没有对其进行任何修改,std::string 的失效规则很复杂)。如果没有未定义的行为,则永远不能使用 b。
Data.str() is a temporary, which is destroyed at the end of this statement; the value of that temporary's c_str() can only be used while the temporary is alive (and you've made no modifications to it, the invalidation rules are complex for std::string). You can never use b without Undefined Behavior.
我假设您确实想将字符串“
12
”写入字符串流。仅通过转换int
int
12
转换为char*
code> 到char*
。也就是说,我相信你的这部分可能是不正确的:如果 dataLength 确实是一个 int,那么这不是将其转换为
char*
的正确方法。也许是这样:我希望我没有完全误解你想要实现的目标。
I assume you really want to write the string "
12
" into the stringstream. You can't convert theint
12
to achar*
by merely casting theint
tochar*
. That is, I believe this part of your might be incorrect:If dataLength is really an int, this is not the correct way to turn it into a
char*
. Perhaps this:I hope I haven't totally misunderstood what you're trying to achieve.