Reputation: 45
Although the value of the bbuf and hbuff is different but nothing happening for the 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;
But it work after the following line is removed
hdevi.ReadBuffer(hbuff[0],length(hbuff));
or add this line hdevi.Position:=0;
before
hdevi.WriteBuffer(bbuff[0],length(bbuff));
I don't know why, can someone explain for me?
Upvotes: 0
Views: 350
Reputation: 21045
I don't know why, can someone explain for me?
Every TStream
descendant has a Position
property which indicates at what byte position in the stream a following read or write operation will take place. For each read or write operation the Position
is advanced with the number of bytes read or written. To change the Position
you can either assign to Position
or call the Seek()
function directly (Position
uses internally the Seek()
function).
Let's look at these three lines of your code:
// 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
Obviously you wanted to write the 512 bytes from bbuff
to the beginning of hdevi
.
As you have found out you can either skip the reading into hbuff
altogether (in which case hdevi.Position
is at 0) or if you need to read the hbuff
buffer first, you must reset the hdevi.Position
to 0.
Upvotes: 2
Reputation: 581
Each time you call WriteBuffer
or ReadBuffer
the pointer to the position you are currently at the stream is moved forward by length(...)
. Therefore moving the position back to 0 (Have a look at the Seek
method of TStream
, see documentation here) your code is working.
Upvotes: 3