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.