Delphi 创建目录及写日志文件、写INI文件

来源:互联网 发布:数学辅导软件 编辑:程序博客网 时间:2024/05/16 10:41

/_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文件的代码:

 withTIniFile.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;

 

  //写

  withTIniFile.Create(_AppPath + 'F7.INI') do
  begin
    for i := 0to 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就可以明显感觉出来了。
原创粉丝点击