是否可以从文件开头删除字节? [英] Is it possible to delete bytes from the beginning of a file?

查看:134
本文介绍了是否可以从文件开头删除字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以有效地截断文件并从文件末尾删除字节。

I know that I can efficiently truncate a file and remove bytes from the end of the file.

是否存在通过删除文件开头到文件中间的内容来截断文件的有效方法?

Is there a corresponding efficient way to truncate files by deleting content from the beginning of the file to a point in the middle of the file?

推荐答案

在我阅读此问题时,您要从文件的开头开始从文件中删除内容。换句话说,您希望删除文件开头的内容,然后将剩余内容向下移动。

As I read the question you are asking to remove content from a file starting from the beginning of the file. In other words you wish to delete content at the start of the file and shift the remaining content down.

这是不可能的。您只能从头开始截断文件,而不能从头开始截断。您将需要将其余内容复制到一个新文件中,或将其复制到同一文件中。

This is not possible. You can only truncate a file from the end, not from the beginning. You will need to copy the remaining content into a new file, or copy it down yourself within the same file.

但是,这样做没有快捷有效的方法这个。您必须复制数据,例如,如@kobik所述。

However you do it there is no shortcut efficient way to do this. You have to copy the data, for example as @kobik describes.

Raymond Chen在此主题上写了一篇不错的文章:如何从文件开头删除字节?

Raymond Chen wrote a nice article on this topic: How do I delete bytes from the beginning of a file?

这只是一个有趣的操作,它是基于流的方法的简单实现,可从文件中的任何位置删除内容。您可以将其与读/写文件流一起使用。我还没有测试代码,我就把它留给你!

Just for fun, here's a simple implementation of a stream based method to delete content from anywhere in the file. You could use this with a read/write file stream. I've not tested the code, I'll leave that to you!

procedure DeleteFromStream(Stream: TStream; Start, Length: Int64);
var
  Buffer: Pointer;
  BufferSize: Integer;
  BytesToRead: Int64;
  BytesRemaining: Int64;
  SourcePos, DestPos: Int64;
begin
  SourcePos := Start+Length;
  DestPos := Start;
  BytesRemaining := Stream.Size-SourcePos;
  BufferSize := Min(BytesRemaining, 1024*1024*16);//no bigger than 16MB
  GetMem(Buffer, BufferSize);
  try
    while BytesRemaining>0 do begin
      BytesToRead := Min(BufferSize, BytesRemaining);
      Stream.Position := SourcePos;
      Stream.ReadBuffer(Buffer^, BytesToRead);
      Stream.Position := DestPos;
      Stream.WriteBuffer(Buffer^, BytesToRead);
      inc(SourcePos, BytesToRead);
      inc(DestPos, BytesToRead);
      dec(BytesRemaining, BytesToRead);
    end;
    Stream.Size := DestPos;
  finally
    FreeMem(Buffer);
  end;
end;

这篇关于是否可以从文件开头删除字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆