从TextFile中删除前N个字符而不创建新文件(Delphi)

Som*_*One 6 delphi pascal text-files

我只是想从指定的文本文件中删除前N个字符,但我卡住了.请帮帮我!

procedure HeadCrop(const AFileName: string; const AHowMuch: Integer);
var
  F: TextFile;
begin
  AssignFile(F, AFileName);
  // what me to do next?
  // ...
  // if AHowMuch = 3 and file contains"Hello!" after all statements
  // it must contain "lo!"
  // ...
  CloseFile(F);
end;
Run Code Online (Sandbox Code Playgroud)

我试图使用TStringList,但它还附加了行尾字符!

with TStringList.Create do
try
  LoadFormFile(AFileName); // before - "Hello!"
  // even there are no changes...
  SaveToFile(AFileName); // after - "Hello!#13#10"
finally
  Free;
end;
Run Code Online (Sandbox Code Playgroud)

谢谢!

gab*_*abr 9

从Windows中的文件开头删除一些东西没有简单的方法.您必须将文件复制到另一个文件,删除原始文件并重命名目标文件,或者将文件中的所有数据复制回几个字节,然后截断文件.如果文件很小并且可以加载到内存中,后一种方法就变得非常简单了.

以下代码片段使用全尺寸内存缓冲区实现后一种方法.

var
  fs: TFileStream;
  ms: TMemoryStream;

begin
  fs := TFileStream.Create('somefile', fmOpenReadWrite); // catch errors here!
  try
    ms := TMemoryStream.Create;
    try
      ms.CopyFrom(fs, 0);
      ms.Position := 42; // head bytes to skip
      fs.Position := 0;
      fs.CopyFrom(ms, ms.Size - ms.Position);
      fs.Size := fs.Position;
    finally FreeAndNil(ms); end;
  finally FreeAndNil(fs); end;
end;
Run Code Online (Sandbox Code Playgroud)