在Delphi 2010中写一个字符串到TFileStream [英] Writing a string to a TFileStream in Delphi 2010

查看:1351
本文介绍了在Delphi 2010中写一个字符串到TFileStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Delphi 2007代码如下:

  procedure WriteString(Stream:TFileStream; var SourceBuffer:PChar; s :string); 
begin
StrPCopy(SourceBuffer,s);
Stream.Write(SourceBuffer [0],StrLen(SourceBuffer));
结束

我称之为:

  var 
SourceBuffer:PChar;
MyFile:TFileStream;

....

SourceBuffer:= StrAlloc(1024);
MyFile:= TFileStream.Create('MyFile.txt',fmCreate);
WriteString(MyFile,SourceBuffer,'Some Text');
....

这在Delphi 2007中有效,但它给了我很多Delphi 2010中的垃圾字符。我知道这是由于unicode合规性问题,但我不知道如何解决这个问题。



这是我试过的far:





我做错了什么?

解决方案

您不需要单独的缓冲区来将字符串写入流。可能最简单的方法是将字符串编码为UTF8,如下所示:

  procedure TStreamEx.writeString(const data:串); 
var
len:cardinal;
oString:UTF8String;
begin
oString:= UTF8String(data);
len:= length(oString);
self.WriteBuffer(len,4);
如果len> 0然后
self.WriteBuffer(oString [1],len);
结束

函数TStreamEx.readString:string;
var
len:integer;
iString:UTF8String;
begin
self.readBuffer(len,4);
如果len> 0然后
begin
setLength(iString,len);
self.ReadBuffer(iString [1],len);
result:= string(iString);
结束
结束

我已经将TStreamEx声明为TStream的类帮助器,但不应该太难将这些重写为独立程序和函数,就像您的示例。


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 PWideChar

  • Every one of the suggestions listed here

What am I doing wrong?

解决方案

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:

procedure TStreamEx.writeString(const data: string);
var
   len: cardinal;
   oString: UTF8String;
begin
   oString := UTF8String(data);
   len := length(oString);
   self.WriteBuffer(len, 4);
   if len > 0 then
      self.WriteBuffer(oString[1], len);
end;

function TStreamEx.readString: string;
var
   len: integer;
   iString: UTF8String;
begin
   self.readBuffer(len, 4);
   if len > 0 then
   begin
      setLength(iString, len);
      self.ReadBuffer(iString[1], len);
      result := string(iString);
   end;
end;

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中写一个字符串到TFileStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆