关于字符串在流中的读写问题(50分)

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

sweidong

Unregistered / Unconfirmed
GUEST, unregistred user!
unit Unit1;

interface

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

type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
Edit3: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var
hstream:Tfilestream;
str:string;
ite,strcount:integer;
begin
if savedialog1.Execute then
hstream:=Tfilestream.Create(savedialog1.filename,fmopenwrite or fmcreate);
ite:=strtoint(edit1.Text);
hstream.Write(ite,sizeof(integer));
str:=edit2.text;
strcount:=length(str);
hstream.write(strcount,sizeof(integer));
hstream.write(str[1],strcount);
hstream.Free;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
hstream:Tfilestream;
str:pchar;
ite,strcount:integer;
str1:string;
begin
if opendialog1.Execute then
hstream:=Tfilestream.Create(opendialog1.filename,fmopenread);
hstream.Read(ite,sizeof(integer));
edit1.text:=inttostr(ite);
hstream.Read(strcount,sizeof(integer));
//edit3.text:=inttostr(strcount);
getmem(str,strcount);
hstream.read(str,strcount);
str1:=str;
edit2.text:=str1;
hstream.Free;
end;

end.
写没问题,读出错!请指教!
 
我建议你最好用一个结构来读写数据,这样方便的多,而且容易控制
writerecord=record
data:intger;
end;
var
str:writerecord;
hstream.read(str,sizeof(str));
再读写就方便多了
 
错在这里:
getmem(str,strcount);
hstream.read(str,strcount);
---->
setlength(str, strcount);
hstream.read(str[1], strcount);
 
hstream.read(str,strcount);
把这句改为:
hstream.read(str^,strcount);
或者这样:
Setlength(Str1, strcount);
hstream.read(str1[1],strcount);
 
谢谢大家!
 

Similar threads

后退
顶部