我想做的基本上是写我的VCL应用程序的日志文件。日志记录程序必须在给定的位置创建文本文件,其名称将包含当前的写作日期,示例为“BSSGLog 20231106.txt”。为了使它更容易通过日志文件,如果需要的话,我想限制条目的文本1000行。如果有溢出,在当前日期,然后它必须创建新的文件添加扩展名,例如“BSSGLog 20231106_1.txt”等。它工作正常,直到它达到扩展名“_9”,之后,它创建扩展名为“_10”的文件,但它只写一行文本,并创建“_11”。它一直创建只有一行文本的文件,直到它达到“_89”.之后,它再次正常工作.我知道问题在于过程 SearchFiles,因为它不断检查文件扩展名为“_9”一遍又一遍.这是代码,使它更容易理解我想做什么.
function SearchFiles(SearchDir, SearchFile: string):String;
var
SearchRec: TSearchRec;
begin
if FindFirst(SearchDir + SearchFile, faAnyfile, SearchRec) = 0 then
begin
repeat
Result := SearchRec.Name
until (FindNext(SearchRec)<>0);
end;
FindClose(SearchRec);
end;
procedure Log(s: string);
var
FileCont: TStringList;
FileName, LogEntry: String;
fs: Tformatsettings;
i: Integer;
begin
DeleteFilesOlderThan30Days;
if not DirectoryExists(TPath.GetHomePath() + '\test') then
CreateDir(TPath.GetHomePath() + '\test');
if not DirectoryExists(TPath.GetHomePath() + '\test\Logs') then
CreateDir(TPath.GetHomePath() + '\test\Logs');
FileCont := TStringList.Create;
try
fs.ShortDateFormat := 'YYYYMMDD';
fs.TimeSeparator := ':';
if SearchFiles(TPath.GetHomePath() + '\test\Logs\', 'BSSGLog ' + DateToStr(now,fs) + '.txt') = '' then // I believe the problem lies here
begin
Filename := TPath.GetHomePath() + '\test\Logs\BSSGLog ' + DateToStr(Now, fs) + '.txt';
fileCont.SaveToFile(filename);
end
else
Filename := TPath.GetHomePath() + '\test\Logs\' + SearchFiles(TPath.GetHomePath() +
'\test\Logs\', 'BSSGLog ' + DateToStr(now,fs) + '*.txt');
FileCont.LoadFromFile(FileName);
if FileCont.Count >= 1000 then
begin
i := GetFilesCount(TPath.GetHomePath() + '\test\Logs\', 'BSSGLog ' + DateToStr(now,fs) + '*.txt');
Filename := TPath.GetHomePath() + '\test\Logs\BSSGLog ' + DateToStr(Now, fs) + '_' + i.ToString + '.txt';
FileCont.Clear();
end;
fs.ShortDateFormat := 'DD.MM.YYYY. HH:mm:ss';
LogEntry := DateTimeToStr(Now(), fs) + '- ' + s;
FileCont.Add(LogEntry);
FileCont.SaveToFile(Filename);
finally
FreeAndNil(FileCont);
end;
end;
function GetFilesCount(SearchDir, SearchFile : String) : Integer;
var
SearchRec: TSearchRec;
begin
Result := 0;
if FindFirst(SearchDir + SearchFile, faAnyFile xor faDirectory, SearchRec)= 0 then
begin
repeat
Inc(Result);
until (FindNext(SearchRec) <> 0);
FindClose(SearchRec);
end;
end;
字符串
任何建议将高度赞赏。也许是一个想法,如何做一个更好的工作在伐木。提前感谢你!
2条答案
按热度按时间ep6jt1vc1#
你应该摆脱函数
SearchFiles
,因为排序问题,你应该利用FileExists
函数。考虑到你的代码,这是我如何修改它:字符串
我没试过。如果对你有效就告诉我。
1yjd4xko2#
在
function SearchFiles(SearchDir, SearchFile: string):String;
中,您将浏览搜索结果并输出符合条件的最后一个文件。然而,这可能不是最后创建的文件。文件的顺序没有定义,您应该收集所有文件名,检查它们并决定其中一个是最后一个并将其输出。请参阅Is FindFirst supposed to return found files in Alphabetical order?