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.

posted on 2008-01-01 21:52  万一  阅读(9086)  评论(16编辑  收藏  举报