===请教关于读写字符串的问题===(50分)

  • 主题发起人 主题发起人 pjYan
  • 开始时间 开始时间
P

pjYan

Unregistered / Unconfirmed
GUEST, unregistred user!
用TFileStream,代码如下:

var
stream: TFileStream;
str: string;
len: Integer;
begin
str := 'test string';
len := StrLen(PChar(str));
stream := TFileStream.Create('test', fmCreate);
stream.Write(len, SizeOf(len));
stream.Write(str, len);
stream.Destroy;

stream := TFileStream.Create('test', fmOpenRead);
stream.Read(len, SizeOf(len));
SetLength(str, len);
stream.Read(str, len);
stream.Destroy;
end;

这段代码是错的,
但是要怎么改才对呢?
请大侠详细讲讲,
不才有理了!
 
var
stream: TFileStream;
str: PChar
// Modified
len: Integer;
begin
str := 'test string';
len := StrLen(str)
// Modified
stream := TFileStream.Create('test', fmCreate);
stream.Write(len, StrLen(len))
// Modified
stream.Write(str, len);
stream.Destroy;

str = ''
// This is additional line

stream := TFileStream.Create('test', fmOpenRead);
stream.Read(len, (len));
SetLength(str, len);
stream.Read(str, len);
stream.Destroy;
end;

 
吾来灌灌水,

对流操作时要注意流的位置
 
接受答案了.
 
我试了一下,这样写的,各位大虾也帮忙看看有什么不妥

var
stream: TFileStream;
str: PChar
// Modified
len: Integer;
begin
str := 'test string';
len := strlen(str)
// Modified
stream := TFileStream.Create('d:/ss.dat', fmCreate);
stream.Write (len,sizeof(integer));
stream.Write(str, len);
stream.free;

str:= ''
// This is additional line

stream := TFileStream.Create('d:/ss.dat', fmOpenRead);
stream.Read(len, sizeof(integer));
stream.Read(str, len);
showmessage(str);
stream.free;
end;
-----------

 
后退
顶部