天天看點

Delphi 建立目錄及寫日志檔案、寫INI檔案

/_AppPath 全局變量

_AppPath := ExtractFilePath(ParamStr(0));

1、定義類型

var

  F: TextFile;

  LogFile: string;

  txt :string;

2、代碼

  //建立目錄

  if not directoryexists(_AppPath + 'Error/') then

    createdir(_AppPath + 'Error/');

  LogFile :=  _AppPath + 'Error/' + FormatDateTim('YYYYMMDD',Date) + '.txt';

 //寫日志檔案

  AssignFile(F, LogFile);

  if FileExists(LogFile) then

    Append(F)

  else

    Rewrite(F);

  //開始寫入

  Writeln(F, txt);

  //結束

  CloseFile(F);

另外附加一段寫INI檔案的代碼:

 with TIniFile.Create(_AppPath + 'F7.INI') do

  begin

    //讀    

    AutoTime := ReadInteger('System','AutoTime', 900000);

    nCount := ReadInteger('TIMELIST1', 'COUNT', 0);

    if nCount > 0 then

    begin

      TimeList1.Lines.Clear;

      for i := 0 to nCount - 1 do

        TimeList1.Lines.Add(ReadString('TIMELIST1', IntToStr(i),''));

    end;

    Free;

  end;

  //寫

  with TIniFile.Create(_AppPath + 'F7.INI') do

  begin

    for i := 0 to TimeList1.Lines.Count -1 do

    begin

      s := Trim(TimeList1.Lines.Strings[i]);

      if s <> '' then

      begin

        Inc(j);

        WriteString('TIMELIST1', IntToStr(i), s);

      end;

    end;

    WriteInteger('TIMELIST1', 'COUNT', j);

    Free;

  end;

我寫了一個函數用來寫日志,但是寫的時候提示出錯。I/O error 32。我查了下錯誤原因應該是定時器同時寫入的問題,然後我用了2中線程方法處理,但是都沒用,結果一樣,幫忙看下怎麼回事。
procedure TEventLog.RecordLog(Log: string);
var
    f:Textfile;
    FileName:string;
    name:string;
begin
    if WaitForSingleObject(hMutex, INFINITE) = WAIT_OBJECT_0 then 
    begin
        name:=FormatDateTime('yyyymmdd',now);
        FileName:=ExtractFilePath(Paramstr(0))+'log/'+name+'.log';                    //儲存檔案名
        AssignFile(f, FileName);
        try
            if FileExists(FileName)= False then
                Rewrite(f)
            else
                Append(f);
            Writeln(f,FormatDateTime('yy''-''mm''-''dd hh:nn:ss ',Now) + Log);
        finally
            CloseFile(f);
        end;
        ReleaseMutex(hMutex); 
    end;
end;

procedure TEventLog.RecordLog(Log: string);
var
    f:Textfile;
    FileName:string;
    name:string;
begin
    criticalsection.enter;
    try
        name:=FormatDateTime('yyyymmdd',now);
        FileName:=ExtractFilePath(Paramstr(0))+'log/'+name+'.log';                    //儲存檔案名
        AssignFile(f, FileName);
        try
            if FileExists(FileName)= False then
                Rewrite(f)
            else
                Append(f);
            Writeln(f,FormatDateTime('yy''-''mm''-''dd hh:nn:ss ',Now) + Log);
        finally
            CloseFile(f);
        end; 
    finally
        criticalsection.leave;
    end;
end;      

最佳答案

出錯原因:因為通路檔案的方式是獨占式,兩個地方同時通路了這個檔案。

    将 Textfile 設定為全局變量,程式初始化時,載入Textfile,将所有寫Textfile 檔案的操作,都由一個函數來執行,程式關閉時才CloseFile(Textfile) 。

    追加檔案内容速度很快,但是載入檔案和關閉檔案是非常緩慢的,這兩過程所消耗的時間非常巨大的。一直載入/關閉的話,一點效率也沒有。小檔案還行,隻要上M就可以明顯感覺出來了。      

繼續閱讀