【发布时间】:2013-03-17 17:10:46
【问题描述】:
我有一个二进制文件 (2.5 MB),我想找到这个字节序列的位置:CD 09 D9 F5。然后我想在这个位置之后写一些数据,并用零覆盖旧数据(4 KB)。
这是我现在的做法,但有点慢。
ProcessFile(dataToWrite: string);
var
fileContent: string;
f: file of char;
c: char;
n, i, startIndex, endIndex: integer;
begin
AssignFile(f, 'file.bin');
reset(f);
n := FileSize(f);
while n > 0 do
begin
Read(f, c);
fileContent := fileContent + c;
dec(n);
end;
CloseFile(f);
startindex := Pos(Char($CD)+Char($09)+Char($D9)+Char($F5), fileContent) + 4;
endIndex := startIndex + 4088;
Seek(f, startIndex);
for i := 1 to length(dataToWrite) do
Write(f, dataToWrite[i]);
c := #0;
while (i < endIndex) do
begin
Write(f, c); inc(i);
end;
CloseFile(f);
end;
【问题讨论】:
-
哪部分代码比较慢?你做过计时吗?你怎么知道它很慢?它的速度是多少,您希望能够达到什么目标?
-
按字符读取和写入文件的速度很慢。至少按更大的块将数据提取到缓冲区中(参见 BlockRead)。
-
@DavidHeffernan,是的,它正在搜索序列位置的部分很慢。现在 5 个文件大约需要 15 秒,我希望它最多 1-3 秒。例如,如果我评论它并将 StartIndex 设置为 9999,那么它就是即时的。我认为将所有文件内容逐字节读取为字符+将其复制到字符串不是最佳解决方案。
-
@DavidHeffernan,编译时间。我知道哪个部分很慢,我在上面写过 - 逐字节读取字符串并可能在该字符串中搜索。我希望 blockread 能解决我的问题...
-
哦,天哪,我没有看到你这样做。这绝对是疯了!我会放弃 Pascal I/O。请改用流。
标签: delphi delphi-7 binaryfiles