能不能写一个过程,用来保存任一record(任意类型的) 到指定的文件(50分)

  • 主题发起人 主题发起人 mycoolis
  • 开始时间 开始时间
M

mycoolis

Unregistered / Unconfirmed
GUEST, unregistred user!
用tfilestream来保存
问题是怎么写参数record_的类型?

procedure saverecord(record_:Variant ;filename_:string);
begin
showmessage(inttostr(sizeof(record_ )));
end;

调用的时候出错
 
unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;



var
Form1: TForm1;

implementation

{$R *.dfm}

Function WriteSamFile(const Buffer;WriteLen:integer;FilePath:string):Boolean;//<<<<<<<<
var
sf:TFileStream;
begin
try
sf:=TFileStream.Create(FilePath,fmOpenWrite);
sf.Position := sf.Seek(0,soFromBeginning);
sf.Write(Buffer,WriteLen);
result :=True;
finally
sf.free;
end;
end;

Function ReadSamFile(var Buffer;ReadLen:integer;FilePath:string):Boolean;
var
sf:TFileStream;

begin
try
sf:=TFileStream.Create(FilePath,fmOpenRead);
sf.Position :=Sf.Seek(0,soFromBeginning);
sf.Read(buffer,ReadLen);
result := True;
finally
sf.Free;
end;
end;

type
MyType = record
x,y:Integer;
end;

TextSetup = record
Windows:MyType;
State:Boolean;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
test:TextSetup;
begin
test.State := True;
test.Windows.x := 200;
test.Windows.y := 400;
WriteSamFile(Test,sizeof(TextSetup),'c:/temp/test.Bin');
end;

procedure TForm1.Button2Click(Sender: TObject);
var
GetData:textsetup;
begin

Readsamfile(GetData,sizeof(textsetup),'c:/temp/test.Bin');
showmessage('x:' + inttostr(GetData.Windows.x) + ' y:'
+ Inttostr(GetData.Windows.y));
end;

end.
 
procedure SaveRecord(record_:Pointer ;Length_:Int64;filename_:string);
var
FH:THandle;
buffer:array of byte;
begin
if FileExists(filename_) then
Exit;
FH:=FileCreate(filename_,FILE_SHARE_WRITE);
try
setLength(Buffer,Length_);
CopyMemory(@Buffer[0],record_,Length_);
FileSeek(FH,0,0);
FileWrite(FH,Buffer[0],Length_);
finally
CloseHandle(FH);
end;
end;


type
TP=record //随你设置
fi:integer;
fs:string[2];//一定要用定长字符串,否则该字段存储的就是指针
ff:real;
end;


var
p:tp;
begin
p.fi :=100;
p.fs :='ab';
p.ff :=1.2;
SaveRecord(@p,Sizeof(tp),'c:/a');
end;
 
忘了想到 record也有指针、record 也可以作为buffer传递
特此鸣谢 gonghh 和 wr960204!
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
I
回复
0
查看
415
import
I
后退
顶部