Y
yousp
Unregistered / Unconfirmed
GUEST, unregistred user!
[!]偶想使用Delphi来读取某个Web服务器的Log文件,此时该服务器已经打开了该Log文件,<br>并且不断将内容写入该文件,我用了以下好几种方法尝试均无法打开该文件。但是,<br>我使用Notepad或者Editplus编辑器却可以将其打开,不知道他们使用的是什么API?<br><br>我用的方法:(我开始直接使用TMemo.lines.loadFromFile(fileName)去打开该文件,<br>结果失败,因此使用TMemoryStream去打开,仍然失败,最后使用TFileStream还是失败)[h1][/h1]<br><br>程序如下:<br>unit FrmMain;<br><br>interface<br><br>uses<br> Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br> Dialogs, Menus, StdCtrls, ExtCtrls;<br><br>type<br> TFormMain = class(TForm)<br> MemoConsole: TMemo;<br> MainMenu: TMainMenu;<br> TopMenuFile: TMenuItem;<br> MenuItemOpen: TMenuItem;<br> MenuItemExit: TMenuItem;<br> OpenDialog: TOpenDialog;<br> Timer: TTimer;<br><br> procedure MenuItemOpenClick(Sender: TObject);<br> procedure TimerTimer(Sender: TObject);<br> procedure FormCreate(Sender: TObject);<br> procedure FormDestroy(Sender: TObject);<br> private<br> { Private declarations }<br> FLogFileName: String;<br> FBuf: TMemoryStream;<br> public<br> { Public declarations }<br> function GetStream(const FileName: String): Boolean;<br> end;<br><br>var<br> FormMain: TFormMain;<br><br>implementation<br><br>{$R *.dfm}<br><br>//从FLogFileName获取一个TStream<br>function TFormMain.GetStream(const FileName: String): Boolean;<br>var<br> FileStream: TFileStream;<br>begin<br> if not FileExists(FileName) then<br> begin<br> Result := false;<br> Exit;<br> end;<br><br> try<br> try<br> FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareCompat);<br> FBuf.LoadFromStream(FileStream);<br> except<br> MessageBox(Handle, PChar('无法打开文件:' + FLogFileName),<br> '打开日志文件错误', MB_ICONERROR);<br> Result := false;<br> Timer.Enabled := false;<br> FileStream.Free;<br> Exit;<br> end;<br> finally<br> FileStream.Free;<br> end;<br> Result := true;<br>end;<br><br>procedure TFormMain.MenuItemOpenClick(Sender: TObject);<br>begin<br> with OpenDialog do<br> begin<br> Filter := '日志文件(*.log)|*.log|所有文件(*.*)|*.*';<br> if Execute then<br> begin<br> FLogFileName := FileName;<br> Timer.Enabled := true;<br> end;<br> end;<br>end;<br><br>procedure TFormMain.TimerTimer(Sender: TObject);<br>begin<br> if GetStream(FLogFileName) then<br> begin<br> MemoConsole.Lines.LoadFromStream(FBuf);<br> Timer.Enabled := false;<br> end;<br>end;<br><br>procedure TFormMain.FormCreate(Sender: TObject);<br>begin<br> FBuf := TMemoryStream.Create;<br>end;<br><br>procedure TFormMain.FormDestroy(Sender: TObject);<br>begin<br> FBuf.Free;<br>end;<br><br>end.