程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> 關於 Delphi 中流的使用(3) 通過內存流讀取文件

關於 Delphi 中流的使用(3) 通過內存流讀取文件

編輯:Delphi

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. 


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved