unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, SyncObjs;
type
TForm1 = class(TForm)
Button1 : TButton;
Memo1 : TMemo;
Memo2 : TMemo;
procedure FormCreate(Sender : TObject);
procedure Button1Click(Sender : TObject);
procedure FormClose(Sender : TObject;
var Action : TCloseAction);
Private
{ Private declarations }
Public
{ Public declarations }
fsFileStream : TFileStream;
ReadStr : string;
FileLine : string;
iReadLen : integer;
FCS : TCriticalSection;
function GetDataLine : string;
end;
TMyThread = class(TThread)
FMemo : TMemo;
Public
constructor Create(AMemo : TMemo);
procedure Execute;
Override;
end;
var
Form1 : TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender : TObject);
begin
fsFileStream := TFileStream.Create('D:/1', fmOpenRead or
fmSharedenyNone);
FCS := TCriticalSection.Create;
end;
function TForm1.GetDataLine : string;
var
iPos : integer;
n : integer;
begin
FCS.Enter;
try
while (Pos(#13#10, FileLine) = 0) and (fsFileStream.Size - iReadLen > 0)
do
begin
SetLength(ReadStr, 30);
ZeroMemory(@ReadStr[1], 30);
if (fsFileStream.Size - iReadLen) >= 30 then
begin
fsFileStream.ReadBuffer(ReadStr[1], 30);
iReadLen := iReadLen + 30;
end
else
begin
n := fsFileStream.Size - iReadLen;
fsFileStream.ReadBuffer(ReadStr[1], n);
iReadLen := fsFileStream.Size;
end;
FileLine := FileLine + ReadStr;
end;
iPos := Pos(#13#10, FileLine);
Result := Copy(FileLine, 1, iPos - 1);
Delete(FileLine, 1, iPos + 1);
finally
FCS.Leave
end;
end;
procedure TForm1.Button1Click(Sender : TObject);
begin
TMyThread.Create(Memo1);
TMyThread.Create(Memo2);
end;
{ TMyThread }
constructor TMyThread.Create(AMemo : TMemo);
begin
inherited Create(False);
FMemo := AMemo;
end;
{ TMyThread.Create }
procedure TMyThread.Execute;
var
s : string;
begin
s := Form1.GetDataLine;
while s <> ''do
begin
FMemo.Lines.Add(s);
s := Form1.GetDataLine;
end;
end;
procedure TForm1.FormClose(Sender : TObject;
var Action : TCloseAction);
begin
FCS.Free;
fsFileStream.Free;
end;
end.
临时写的,不知道有没有什么问题。Form1.GetDataLine得出来的就是文本文件的每一行数据了。