Delphi的流(3)--内存流之指针、seek


源代码:
-----------------------------------------------------------------------------------------------

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 Button1Click(Sender: TObject);
   procedure Button2Click(Sender: TObject);
   procedure Button3Click(Sender: TObject);
  private
   { Private declarations }
  public
   constructor Create(AOwner: TComponent); override;
   destructor Destroy; override;

   { Public declarations }
  end;

var
  Form1: TForm1;
  fpath:string;

implementation

{$R *.dfm}
{$APPTYPE CONSOLE}
var
  mStream:TMemoryStream;

{ TForm1 }

constructor TForm1.Create(AOwner: TComponent);
var
  strList:TStringList;
begin
  inherited;
  strList:=TStringList.Create;
  strList.Add('aabbccddeeffgg');
  strList.Add('hhiijjkkllmmnn');
  strList.Add('ooppqqrrssttuu');
  strList.Add('vvwwxxyyzz1122');
  strList.Add('33445566778899');
  fpath:=ExtractFilePath(Application.ExeName)+'test.txt';
  strList.SaveToFile(fpath);

  mStream:=TMemoryStream.Create;
end;

//通过内存流读入memo1
procedure TForm1.Button1Click(Sender: TObject);
begin
  mStream.LoadFromFile(fpath);
  memo1.Lines.LoadFromStream(mStream);
end;

//指针读取流中内容
procedure TForm1.Button2Click(Sender: TObject);
var
  pchar1:PChar;
begin
  mStream.LoadFromFile(fpath);
  pchar1:=mStream.Memory;
  {
  writeln(pchar1^);  //a
  inc(pchar1,2);
  writeln(pchar1^);  //b
  }

  writeln(pchar1[0]);  //a
  writeln(pchar1[16]); //h   注意14,15是10H,13H即回车换行符

end;

procedure TForm1.Button3Click(Sender: TObject);
var
  buf:array[0..1] of char;
begin
  mStream.LoadFromFile(fpath);
  mStream.Seek(0,soFromBeginning);
  mStream.Read(buf,2);
  writeln(buf);    //aa

  mStream.Seek(16,soFromBeginning);
  mStream.Read(buf,2);
  writeln(buf);    //hh

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

end;

destructor TForm1.Destroy;
begin
  mStream.Free;
  inherited;
end;

end.


联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678