如何为WriteBuffer

时间:2016-05-15 03:23:37

标签: delphi

虽然bbuf和hbuff的值不同但hdevi没有发生任何事情。

var
  bfile:    TFileStream;
  hdevi:    TFileStream;
  bbuff:    array[0..511] of byte;
  hbuff:    array[0..87039] of byte;
  curr:     string;
  i:        integer;
begin
  curr:=GetCurrentDir;
  hdevi := TFileStream.Create(PChar(deviceno), fmOpenReadWrite);
  try
    bfile := TFileStream.Create(PChar(curr+'\bfile'), fmOpenReadWrite);
    try
      hdevi.ReadBuffer(hbuff[0],length(hbuff));
      bfile.ReadBuffer(bbuff[0],length(bbuff));
      hdevi.WriteBuffer(bbuff[0],length(bbuff));
      //for i:=0 to length(bbuff)-1 do
      //ShowMessage(IntToHex(hbuff[i],2)+'-'+IntToHex(bbuff[i],2));
    finally
      bfile.Free;
    end
  finally
    hdevi.Free;
  end;
end;

但是在删除以下行后它才有效

hdevi.ReadBuffer(hbuff[0],length(hbuff));

或在

之前添加此行hdevi.Position:=0;
hdevi.WriteBuffer(bbuff[0],length(bbuff));

我不知道为什么,有人可以为我解释一下吗?

2 个答案:

答案 0 :(得分:3)

每次拨打WriteBufferReadBuffer时,指向当前位于流的位置的指针都会向前移动length(...)。因此,将位置移回0(请查看Seek的{​​{1}}方法,请参阅文档here)您的代码正在运行。

答案 1 :(得分:2)

  

我不知道为什么,有人可以为我解释一下吗?

每个TStream后代都有一个Position属性,该属性指示流中的哪个字节位置将发生后续读取或写入操作。对于每次读取或写入操作,Position都会提前读取或写入的字节数。要更改Position,您可以分配到Position或直接调用Seek()函数(Position在内部使用Seek()函数。)

让我们看一下代码的这三行:

  // At this point both hdevi.Position and bfile.Position are 0
  hdevi.ReadBuffer(hbuff[0],length(hbuff));
  // At this point hdevi.Position is 87040
  bfile.ReadBuffer(bbuff[0],length(bbuff));
  // now bfile.Position is 512
  // hdevi.Position is of course still 87040, alas, that's where the bbuff is written
  hdevi.WriteBuffer(bbuff[0],length(bbuff));
  // hdevi.Position is now 87040 + 512 = 87552

显然,您希望将bbuff中的512个字节写入hdevi的开头。 如您所知,您可以完全跳过hbuff的读数(在这种情况下hdevi.Position为0)或者如果您需要先读取hbuff缓冲区,则必须重置hdevi.Position为0。