delphi 删除任意文件的任意位置的任意数量的字符


本文整理自网络,侵删。

  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 批量生成 a到z 字母

Delphi 全局键盘钩子(wh_keyboard)

Delphi 获取两字符串之间的内容

Delphi 压缩图片(bmp、jpg、png)

Delphi 主程序装载脚本

Delphi 消息实现窗口最小化,最大化,关闭(Delphi)

Delphi 实现文件分割合并

Delphi使用sqlite数据库时的中文路径问题

Delphi取得当前目录的上一级目录

Delphi模拟文件拖拽

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...