gpt4 book ai didi

Delphi7 - 如何复制正在写入的文件

转载 作者:行者123 更新时间:2023-12-03 15:57:29 26 4
gpt4 key购买 nike

我有一个应用程序,它每秒将信息记录到主 PC 上的每日文本文件中。网络上使用相同应用程序的从属 PC 想要将此文本文件复制到其本地驱动器。我可以看到将会出现文件访问问题。

这些文件每个不得大于 30-40MB。网络将是 100MB 以太网。我可以看到复制过程可能需要超过 1 秒的时间,这意味着记录 PC 需要在读取文件时打开文件进行写入。

文件写入(记录)和文件复制过程的最佳方法是什么?我知道有标准的 Windows CopyFile() 过程,但这给我带来了文件访问问题。还有使用 fmShareDenyNone 标志的 TFileStream,但这也偶尔会给我带来访问问题(例如每周 1 次)。

完成这项任务的最佳方式是什么?

我当前的文件记录:

procedure FSWriteline(Filename,Header,s : String);
var LogFile : TFileStream;
line : String;
begin
if not FileExists(filename) then
begin
LogFile := TFileStream.Create(FileName, fmCreate or fmShareDenyNone);
try
LogFile.Seek(0,soFromEnd);
line := Header + #13#10;
LogFile.Write(line[1],Length(line));
line := s + #13#10;
LogFile.Write(line[1],Length(line));
finally
logfile.Free;
end;
end else begin
line := s + #13#10;
Logfile:=tfilestream.Create(Filename,fmOpenWrite or fmShareDenyNone);
try
logfile.Seek(0,soFromEnd);
Logfile.Write(line[1], length(line));
finally
Logfile.free;
end;
end;
end;

我的文件复制过程:

procedure DoCopy(infile, Outfile : String);
begin
ForceDirectories(ExtractFilePath(outfile)); //ensure folder exists
if FileAge(inFile) = FileAge(OutFile) then Exit; //they are the same modified time
try
{ Open existing destination }
fo := TFileStream.Create(Outfile, fmOpenReadWrite or fmShareDenyNone);
fo.Position := 0;
except
{ otherwise Create destination }
fo := TFileStream.Create(OutFile, fmCreate or fmShareDenyNone);
end;
try
{ open source }
fi := TFileStream.Create(InFile, fmOpenRead or fmShareDenyNone);
try
cnt:= 0;
fi.Position := cnt;
max := fi.Size;
{start copying }
Repeat
dod := BLOCKSIZE; // Block size
if cnt+dod>max then dod := max-cnt;
if dod>0 then did := fo.CopyFrom(fi, dod);
cnt:=cnt+did;
Percent := Round(Cnt/Max*100);
until (dod=0)
finally
fi.free;
end;
finally
fo.free;
end;
end;

最佳答案

我建议一开始就不要一遍又一遍地关闭和重新打开共享文件。由于您每秒都向其写入数据,因此这是不必要的开销。

在Master端,创建并关闭文件(fmCreate标志不能与其他标志一起使用!),然后在fmOpenWrite中重新打开它。模式为 fmShareDenyWrite共享,保持打开状态,并在需要时写入。

在从机端,打开 fmOpenRead 中的文件模式为 fmShareDenyNone分享,保持打开状态,每秒阅读。无需每次都通过网络复制整个共享文件。那就是浪费带宽。只需读取过去几秒钟内写入的任何新数据即可。如果Slave需要将数据存储在本地文件中,那么它可以独立于共享文件管理一个单独的本地文件,并在需要时将新数据推送到本地文件中。

关于Delphi7 - 如何复制正在写入的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4687654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com