我正在使用文件流从文件中读取和写入数据,但是从我的文件中读取字符串时出现问题。
在测试VCL表单程序中,我写道:
procedure tform1.ReadfromFile4;
var
fs: TFileStream;
arrayString: Array of String;
i, Len1 : Cardinal;
// s : string;
begin
fs := TFileStream.Create('C:\Users\Joe\Documents\Delphi\Streamtest.tst',
fmOpenRead or fmShareDenyWrite);
Memo1.lines.clear;
try
fs.ReadBuffer(Len1, SizeOf(Len1));
SetLength(arrayString, Len1);
FOR i := 0 to Len1-1 do begin
fs.ReadBuffer(Len1, SizeOf(Len1));
SetLength(arrayString[i], Len1);
Fs.ReadBuffer(arrayString[i], Len1);
memo1.lines.add (arrayString[i]);
end;
finally
fs.free;
end;
end;
procedure tform1.WriteToFile4;
var
fs: TFileStream;
arrayString: Array of String;
Len1, c, i: Cardinal;
begin
Memo1.lines.clear;
SetLength(arrayString, 4);
arrayString[0] := 'First string in this Array';
arrayString[1] := 'the Second Array string';
arrayString[2] := 'String number three of this Array';
arrayString[3] := 'this is the fourth String';
fs := TFileStream.Create('C:\Users\Joe\Documents\Delphi\Streamtest.tst',
fmCreate or fmOpenWrite or fmShareDenyWrite);
try
c := Length(arrayString);
Fs.WriteBuffer(c, SizeOf(c));
for i := 0 to c-1 do begin
Len1 := Length(arrayString[i]);
fs.WriteBuffer(Len1, SizeOf(Len1));
if Len1 > 0 then begin
fs.WriteBuffer(arrayString[i], Len1);
end;
end;
finally
fs.free;
end;
end;
“保存”按钮操作正确输入四个字符串,但“加载”按钮(readFromFile4)无法从文件加载字符串。使用Watch列表,我发现为每个字符串正确设置了字符串长度,但访问的数据不是正确的字符串值。我相信我忠实地遵循网站上的说明:http://www.angelfire.com/hi5/delphizeus/customfiles.html] 1在标题为
的部分编写和读取非固定大小变量的动态数组
任何人都可以解释为什么这不能正确读取文件中的字符串?