关于 Delphi 中流的使用(3) 通过内存流读取文件


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  mStream: TMemoryStream;

procedure TForm1.FormCreate(Sender: TObject);
//程序开始先创建一个准备要测试的文件
var
  strList: TStringList;
begin
  strList := TStringList.Create;
  strList.Add('aaaaaaaa');
  strList.Add('bbbbbbbb');
  strList.Add('cccccccc');
  strList.Add('dddddddd');
  strList.SaveToFile('c:\temp\test.txt');
  strList.Free;

  {同时建立内存流}
  mStream := TMemoryStream.Create;
end;


procedure TForm1.Button1Click(Sender: TObject);
//通过流读文件到 Memo
begin
  mStream.LoadFromFile('c:\temp\test.txt'); {把文件读入内存流}
  Memo1.Lines.LoadFromStream(mStream);      {把内存流载入 Memo1}
end;


procedure TForm1.Button2Click(Sender: TObject);
//用字符指针读取流中的内容
var
  pc: PChar;
begin
  pc := mStream.Memory; {把字符指针指向内存流}
  ShowMessage(pc[0]);   {a; 第一个字符}
  ShowMessage(pc[10]);  {b; 这个第二行的第一个字符; 每行8个字再加换行与回车共10个字符}
  ShowMessage(pc[20]);  {c}
  ShowMessage(pc[30]);  {d}
end;


procedure TForm1.Button3Click(Sender: TObject);
//从流读入到缓冲区
var
  buffer: array[0..2] of Char; {定义个字符缓冲区}
begin
  mStream.Seek(0, soFromBeginning);
  mStream.Read(buffer, SizeOf(buffer));
  ShowMessage(buffer); {aaa}

  mStream.Seek(10, soFromBeginning);
  mStream.Read(buffer, SizeOf(buffer));
  ShowMessage(buffer); {bbb}

  mStream.Seek(20, soFromBeginning);
  mStream.Read(buffer, SizeOf(buffer));
  ShowMessage(buffer); {ccc}

  mStream.Seek(30, soFromBeginning);
  mStream.Read(buffer, SizeOf(buffer));
  ShowMessage(buffer); {ddd}

{关于 Seek 函数:
  参数1: Offset 是偏移量;
  参数2: Origin 是指针的基准位置, 有三个选值: soFromBeginning、soFromCurrent、soFromEnd
         soFromBeginning: 以开始为基准, 此时参数 Offset 要 >= 0;
         soFromCurrent: 以当前位置为基准;
         soFromEnd: 以结束为基准; 此时参数 Offset 要 <= 0;
  返回: 指针新位置
}
end;


procedure TForm1.FormDestroy(Sender: TObject);
begin
  mStream.Free;
end;

end.

相关