如何读取文件?(50分)

  • 主题发起人 主题发起人 seven_918
  • 开始时间 开始时间
S

seven_918

Unregistered / Unconfirmed
GUEST, unregistred user!
现在我有一个文件,格式如下:<br>&nbsp; 首先是一个头部记录,结构是<br>&nbsp; &nbsp; type<br>&nbsp; &nbsp; &nbsp; header = record<br>&nbsp; &nbsp; &nbsp; &nbsp; a1, a2, a3: Word;<br>&nbsp; &nbsp; &nbsp; end;<br>&nbsp; 接着是正文记录,结构为<br>&nbsp; &nbsp; type<br>&nbsp; &nbsp; &nbsp; test = record<br>&nbsp; &nbsp; &nbsp; &nbsp; b1: string[8];<br>&nbsp; &nbsp; &nbsp; &nbsp; b2: Byte;<br>&nbsp; &nbsp; &nbsp; &nbsp; b3: Word; &nbsp; &nbsp; <br>&nbsp; &nbsp; &nbsp; end;<br>我要怎么样读取这些正文记录呢?<br>要用CreateFile、ReadFile读取,读取文件到一个test结构体的数组中
 
用BlockRead读取记录文件,举个例子:<br><br>unit Unit1;<br><br>interface<br><br>uses<br>&nbsp; Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,<br>&nbsp; StdCtrls;<br><br>type<br>&nbsp; TForm1 = class(TForm)<br>&nbsp; &nbsp; Button1: TButton;<br>&nbsp; &nbsp; Memo1: TMemo;<br>&nbsp; &nbsp; Memo2: TMemo;<br>&nbsp; &nbsp; Button2: TButton;<br>&nbsp; &nbsp; procedure Button1Click(Sender: TObject);<br>&nbsp; private<br>&nbsp; &nbsp; { Private declarations }<br>&nbsp; &nbsp; procedure ShowData;<br>&nbsp; public<br>&nbsp; &nbsp; { Public declarations }<br>&nbsp; end;<br><br>type<br>&nbsp; TMyData = packed record<br>&nbsp; &nbsp; w: packed array[0..2]of word;<br>&nbsp; &nbsp; dw: packed array[0..8]of dword;<br>&nbsp; end;<br><br>var<br>&nbsp; Form1: TForm1;<br>&nbsp; f:file of TMyData;<br>&nbsp; Data: TMyData;<br>implementation<br><br>{$R *.DFM}<br><br>procedure TForm1.ShowData;<br>begin<br>&nbsp; with Data do<br>&nbsp; memo1.Lines.Add(format('w1:%g,w2:%g,w3:%g,dw1:%g,dw2:%g,dw3:%g',[w[0]/100,w[1]/100,w[2]/100,dw[0]/100000,dw[1]/100000,dw[2]/100000]));<br>end;<br><br>procedure TForm1.Button1Click(Sender: TObject);<br>var<br>&nbsp; NumRead:integer;<br>begin<br><br>&nbsp; caption := inttostr(Sizeof(Data));<br>&nbsp; assignfile(f,'T0105.101');<br>&nbsp; Reset(f);<br>&nbsp; BlockRead(f,Data,Sizeof(Data),NumRead);<br>&nbsp; closefile(f);<br>&nbsp; ShowData;<br><br>end;<br><br>end.<br>
 
上面的这种方法很好,你也可以采用二进制文件的读写方式进行。
 
to zw84611:<br>我是想知道如何用CreateFile、ReadFile来读取,我就是不知道该怎样调用ReadFile这个<br>API函数。<br>还有,我的文件是包含一个头部记录,就好象是<br>1,2,3,'abcabcab',1,1,'asdasdas',2,2,……
 
http://www.delphibbs.com/delphibbs/dispq.asp?lid=0254993
 
从数据库读取文件到本地硬盘和从本地硬盘读取文件到数据库<br>在数据库上使用Image二进制字段保存,使用Stream流的方式。<br>创建文件流:<br>Word_FileStream:=TFileStream.Create(Target_Name,fmOpenWrite or fmCreate);<br>Word_FileStream.Position:=0;<br>保存到数据库的Image字段:<br>TBlobField(AdoQuery1.FieldByName(Column_Name)).SaveToStream(Word_FileStream);<br>从数据库读取文件到本地硬盘:<br>TBlobField(ADOQuery1.FieldByName(Column_Name)).loadfromStream(Word_FileStream);<br>释放文件流:<br>Word_FileStream.Free;<br>
 
用TFileStream 比较好
 
多人接受答案了。
 
后退
顶部