本文整理自网络,侵删。
function DelChar(AFile: string; DelStart, DelCount: integer): integer;
//如果作为窗体的过程,过程名前要加窗体的类名,比如 TForm1.DelChar
//AFile 是欲处理的文件,DelStart 是欲删除字符的开始位置,DelCount 是欲删除的字符数
//注意,DelStart的基数为0
//删除成功,函数返回0,不成功则返回1
//转自 hiya_data 在 CSDN 的回答
var
s1, s2: string;
f1, f2: tFileStream;
c1: PChar;
iRead, iReaded: integer;
k: integer;
SearchRec1: tSearchRec;
begin
Result := 0;
if DelStart < then exit;
try
f1 := tFileStream.Create(AFile, fmOpenRead or fmShareExclusive);
try
if DelStart > (f1.Size-1) then exit;
s2 := ExtractFileName(AFile);
s1 := ExtractFileDir(AFile);
k := 1;
s1 := s1 + 'Bak' + IntToStr(k) + '_' + s2;
while FindFirst(s1, faAnyFile, SearchRec1) = 0 do begin
Inc(k);
s1 := s1 + 'Bak' + IntToStr(k) + '_' + s2;
end;
f2 := tFileStream.Create(s1, fmCreate or fmShareExclusive);
try
f1.Position := 0;
f2.Position := 0;
GetMem(c1, 1024);
iRead := Min(1024, DelStart-f1.Position);
while iRead > 0 do begin
f1.Read(c1^, iRead);
f2.Write(c1^, iRead);
iRead := Min(1024, DelStart-f1.Position);
end;
f1.Position := DelStart + DelCount;
repeat
iReaded := f1.Read(c1^, 1024);
f2.Write(c1^, iReaded);
until (iReaded < 1024) or (f1.Position = f1.Size);
FreeMem(c1);
finally
f2.Free;
end;
finally
f1.Free;
end;
DeleteFile(AFile);
RenameFile(s1, AFile);
except
Result := 1;
end;
end;
相关阅读 >>
Delphi 消息实现窗口最小化,最大化,关闭(Delphi)
更多相关阅读请进入《Delphi》频道 >>