unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo; {添加 Memo 顯示內容}
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TRec = record {定義一個記錄}
name: string[8];
age: Word;
end;
//寫入
procedure TForm1.Button1Click(Sender: TObject);
var
rec: TRec;
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
rec.name := '張三'; rec.age := 8;
ms.Write(rec, SizeOf(rec));
rec.name := '李四'; rec.age := 81;
ms.Write(rec, SizeOf(rec));
rec.name := '王二麻子'; rec.age := 18;
ms.Write(rec, SizeOf(rec));
ms.SaveToFile('c:\temp\rec.dat');
ms.Free;
end;
//讀取
procedure TForm1.Button2Click(Sender: TObject);
var
rec: TRec;
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
ms.LoadFromFile('c:\temp\rec.dat');
Memo1.Clear;
ms.Position := 0;
while ms.Position < ms.Size do
begin
ms.Read(rec, SizeOf(rec));
Memo1.Lines.Add(rec.name + ' ' + IntToStr(rec.age));
end;
{Memo1 的顯示結果會是:
張三 8
李四 81
王二麻子 18
}
ms.Free;
end;
end.