从 TextFile 中删除前 N 个字符而不创建新文件 (Delphi)
我只想从指定的文本文件中删除前 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;
我尝试使用 TStringList 但它另外附加了结束行字符!
with TStringList.Create do
try
LoadFormFile(AFileName); // before - "Hello!"
// even there are no changes...
SaveToFile(AFileName); // after - "Hello!#13#10"
finally
Free;
end;
谢谢!
I just wanna to delete from specified text file first N characters, but i'm stuck. Help me please!
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;
I'm tried to use TStringList but its additionally appends end-line character!
with TStringList.Create do
try
LoadFormFile(AFileName); // before - "Hello!"
// even there are no changes...
SaveToFile(AFileName); // after - "Hello!#13#10"
finally
Free;
end;
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Windows 中,没有简单的方法可以从文件开头删除某些内容。您必须将文件复制到另一个文件,删除原始文件并重命名目标文件,或者将文件中的所有数据复制回几个字节,然后截断该文件。如果文件很小并且可以加载到内存中,则后一种方法就变得相当简单。
以下代码片段使用全尺寸内存缓冲区实现后一种方法。
There's no simple way to delete something from the start of file in Windows. You have to either copy the file to another file, delete the original and rename the target file or copy all the data in the file few bytes back and then truncate the file. If the file is small and can be loaded into memory, the latter method becomes quite simple.
The following code fragment implements the latter approach with a full-size memory buffer.
Gabr 比我先一步,但我采取了另一种方法:
此代码读取文件并将 512 字节的块移回到文件中。
PS:此过程仅移动字节,而不移动字符!所以这只适用于一字节字符。
Gabr beat me to it, but I took another approach:
This code reads the file and moves blocks of 512 bytes back in the file.
PS: this procedure only moves bytes, NOT characters! So this only works for one byte characters.