意外的行为重复使用Delphi中的Tmemorystream
我正在尝试从Tmemorystream读取两条不同长度的字符串,但是这两个流的长度最终都相同。因此,例如,如果第一个字符串是“ abcdefghijkl',而第二个字符串是“ wxyz”,那么我对第二个字符串获得的值是'wxyzefghijkl'(我的新字符串的前四个字符('wxyz')遵循通过“ WXYZ”替换的第一字符串的剩余字符
是: -
var
L : LongInt
S : string;
...
msRecInfo.Position := 0;
msRecInfo.Read(L, SizeOf(L)); // read size of following string ...
SubStream.Clear;
SubStream.CopyFrom(msRecInfo, L); // copy next block of data to a second TMemoryStream
if (L > 0) then S := StreamToString(SubStream); //convert the stream into a string
msRecInfo.Read(L, SizeOf(L)); // get size of following string ...
SubStream.CopyFrom(msRecInfo, L);
if (L > 0) then S := StreamToString(SubStream);
我一直在与这个数小时的战斗而没有成功。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第二个调用
substream.copyfrom()
之前,您没有调用substream.clear()
。因此,第一个调用streamToString(substream)
subssubstream.position.position
在流的末尾,然后是后续substream.copyfrom()
将更多数据添加到流中,保存现有数据。然后,随后的streamTostring(substream)
从substream
中读取所有数据。另外,请注意,如果
l
是0
将其传递给substream.copyfrom()
时,它将复制整个 thother /em>msrecinfo
流。这是记录的行为:因此,您需要向上移动
l> 0
检查,例如:我建议将此逻辑包装到可重复使用的函数中,例如:
虽然,如果可行的话,我建议只能摆脱
substream
完全,更新streamtostring( )
将l
作为输入参数,因此您可以直接从MSRECINFO
直接读取String
,例如:无需2nd
tmemorystream
如果可以避免。You are not calling
SubStream.Clear()
before the 2nd call toSubStream.CopyFrom()
. So, the 1st call toStreamToString(SubStream)
leavesSubStream.Position
at the end of the stream, then the subsequentSubStream.CopyFrom()
adds more data to the stream, preserving the existing data. Then the subsequentStreamToString(SubStream)
reads all of the data fromSubStream
.Also, be aware that if
L
is0
when you pass it toSubStream.CopyFrom()
, it will copy the entiremsRecInfo
stream. This is documented behavior:https://docwiki.embarcadero.com/Libraries/en/System.Classes.TStream.CopyFrom
So, you need to move up your
L > 0
check, eg:I would suggest wrapping this logic into a reusable function, eg:
Although, if feasible, I would suggest just getting rid of
SubStream
altogether, updateStreamToString()
to takeL
as an input parameter, so that you can read thestring
frommsRecInfo
directly, eg:No need for a 2nd
TMemoryStream
if you can avoid it.