2

我正在尝试使用 TFileStream 编写和读取非固定字符串。我收到访问冲突错误。这是我的代码:

// Saving a file
  (...)
  count:=p.Tags.Count; // Number of lines to save (Tags is a TStringList)
  FS.Write(count, SizeOf(integer));
  for j := 0 to p.Tags.Count-1 do
  begin
    str:=p.Tags.Strings[j];
    tmp:=Length(str)*SizeOf(char);
    FS.Write(tmp, SizeOf(Integer));
    FS.Write(str[1], Length(str)*SizeOf(char));
  end;

// Loading a file
  (...)
  p.Tags.Add('hoho'); // Check if Tags is created. This doesn't throw an error.
  Read(TagsCount, SizeOf(integer)); // Number of lines to read
  for j := 0 to TagsCount-1 do
  begin
    Read(len, SizeOf(Integer)); // length of this line of text
    SetLength(str, len); // don't know if I have to do this
    Read(str, len); // No error, but str has "inaccessible value" in watch list
    p.Tags.Add(str); // Throws error
  end;

该文件似乎保存得很好,当我用十六进制编辑器打开它时,我可以找到保存在那里的正确字符串,但是加载会引发错误。

你能帮帮我吗?

4

1 回答 1

8

您保存字节数,这就是您写入的字节数。当您读取该值时,您将其视为字符数,然后读取那么多字节。不过,这不会导致您现在看到的问题,因为您正在使缓冲区大于Delphi 2009 所需的大小。

问题是您正在读取字符串变量,而不是字符串的内容。你str[1]写的时候用过;阅读时也这样做。否则,您将覆盖调用时分配的字符串引用SetLength

Read(nBytes, SizeOf(Integer));
nChars := nBytes div SieOf(Char);
SetLength(str, nChars);
Read(str[1], nBytes);

是的,您确实需要致电SetLength. Read不知道它读到了什么,所以它无法知道它需要提前将大小设置为任何东西。

于 2012-07-16T14:53:50.453 回答