在 Delphi 2010 中将字符串写入 TFileStream
我有 Delphi 2007 代码,如下所示:
procedure WriteString(Stream: TFileStream; var SourceBuffer: PChar; s: string);
begin
StrPCopy(SourceBuffer,s);
Stream.Write(SourceBuffer[0], StrLen(SourceBuffer));
end;
我这样称呼它:
var
SourceBuffer : PChar;
MyFile: TFileStream;
....
SourceBuffer := StrAlloc(1024);
MyFile := TFileStream.Create('MyFile.txt',fmCreate);
WriteString(MyFile,SourceBuffer,'Some Text');
....
这在 Delphi 2007 中有效,但在 Delphi 2010 中给了我很多垃圾字符。我知道这是由于 unicode 合规性问题,但我不确定如何解决这个问题。
这是我到目前为止所尝试过的:
更改的数据类型 SourceBuffer(还有参数 Expected by WideString) 为 PWideChar
列出的每一项建议 这里
我做错了什么?
I have Delphi 2007 code that looks like this:
procedure WriteString(Stream: TFileStream; var SourceBuffer: PChar; s: string);
begin
StrPCopy(SourceBuffer,s);
Stream.Write(SourceBuffer[0], StrLen(SourceBuffer));
end;
I call it like this:
var
SourceBuffer : PChar;
MyFile: TFileStream;
....
SourceBuffer := StrAlloc(1024);
MyFile := TFileStream.Create('MyFile.txt',fmCreate);
WriteString(MyFile,SourceBuffer,'Some Text');
....
This worked in Delphi 2007, but it gives me a lot of junk characters in Delphi 2010. I know this is due to unicode compliance issues, but I am not sure how to address the issue.
Here is what I've tried so far:
Change the data type of
SourceBuffer(and also the parameter
expected by WideString) to PWideCharEvery one of the suggestions listed
here
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要单独的缓冲区来将字符串写入流。也许最简单的方法是将字符串编码为 UTF8,如下所示:
我已将 TStreamEx 声明为 TStream 的类助手,但将它们重写为单独的过程和函数(如您的示例)应该不会太困难。
You don't need a separate buffer to write a string to a stream. Probably the simplest way to do it is to encode the string to UTF8, like so:
I've declared TStreamEx as a class helper for TStream, but it shouldn't be too difficult to rewrite these as a solo procedure and function like your example.
Delphi 2010对此有一个很好的解决方案,记录如下:
http://docwiki.embarcadero .com/CodeExamples/en/StreamStrRdWr_%28Delphi%29
Delphi 2010 has a nice solution for this, documented here:
http://docwiki.embarcadero.com/CodeExamples/en/StreamStrRdWr_%28Delphi%29