1

I have a string that contains null characters.

I've tried to save it to a file with this code:

myStringList.Text := myString;
myStringList.SaveToFile('c:\myfile');

Unfortunately myStringList.Text is empty if the source string has a null character at the beginning.

I thought only C string were terminated by a null character, and Delphi was always fine with it.

How to save the content of the string to a file?

4

3 回答 3

6

我认为您的意思是“保存一个包含#0字符的字符串”。

如果是这种情况,请不要尝试将其放入TStringList. 实际上,根本不要尝试将其保存为字符串;就像在 C 中一样,NULL 字符(#0在 Delphi 中)有时会导致字符串被截断。使用 aTFileStream并将其直接写为字节内容:

var
  FS: TFileStream;
begin
  FS := TFileStream.Create('C:\MyFile', fmCreate);
  try
    FS.Write(myString[1], Length(myString) * SizeOf(Char));
  finally
    FS.Free;
  end;
end;

读回来:

var
  FS: TFileStream;
begin
  FS := TFileStream.Create('C:\MyFile', fmOpenRead);
  try
    SetLength(MyString, FS.Size);
    FS.Read(MyString[1], FS.Size);
  finally
    FS.Free;
  end;
end;
于 2013-01-27T01:22:51.853 回答
5

当您设置对象的Text属性时TStrings,新值将被解析为以空字符结尾的字符串。因此,当代码到达您的空字符时,解析将停止。

我不确定为什么 Delphi RTL 代码是这样设计的,并且没有记录,但这就是设置Text属性的工作方式。

您可以通过使用Add方法而不是Text属性来避免这种情况。

myStringList.Clear;
myStringList.Add(myString);
myStringList.SaveToFile(FileName);
于 2013-01-27T09:28:01.803 回答
3

关于一般将字符串写入文件。我仍然看到人们创建流或字符串列表只是为了将一些内容写入文件,然后销毁流或字符串列表。

Delphi7 还没有 IOUtuls.pas,但你错过了。

有一个方便的带有类方法的 TFile 记录,可让您使用单行将文本写入文件,而无需临时变量:

TFile.WriteAllText('out.txt','hi');

升级使您作为 Delphi 开发人员的生活更加轻松。这只是一个很小的例子。

于 2013-01-27T17:18:51.193 回答