大概写了一个,将就着用吧.
//AStream 进行删除操作的 TStream 实例
//从 Stream 中 Position 为 Index 处开始删除 Count 个字节.注意 Index 从 0 开始.
procedure StreamDelete(AStream: TStream
Index: Longint
Count: Longint);
var
SavedPos: Longint;
ASize: Longint;
BufferStream: TMemoryStream;
begin
if not Assigned(AStream) then
exit;
ASize := AStream.Size;
if (Index >= ASize) or (Count = 0) then
exit;
if (Index + Count) >= ASize then
begin
AStream.Size := Index;
exit;
end
else begin
SavedPos := AStream.Position;
try
AStream.Seek(Index + Count, soFromBeginning);
BufferStream := TMemoryStream.Create;
try
ASize := ASize - (Index + Count);
BufferStream.SetSize(ASize);
BufferStream.Seek(0, soFromBeginning);
BufferStream.CopyFrom(AStream, ASize);
AStream.Size := Index + ASize;
AStream.Seek(Index, soFromBeginning);
AStream.Write(BufferStream.Memory^, ASize);
finally
BufferStream.Free;
end;
finally
AStream.Position := SavedPos;
end;
end;
end;
用法:
var
FileStream: TFileStream;
...
//对 TFileStream, OpenMode 必须为 fmOpenReadWrite,保证可读写.
FileStream := TFileStream.Create('c:/aaa.txt', fmOpenReadWrite);
StreamDelete(FileStream, 10, 5)
//从 Position 为 10(第 11 个字节)起删除 5 bytes.
...