Writing a string to a TFileStream in Delphi 2010

前端 未结 2 1617
不思量自难忘°
不思量自难忘° 2021-02-07 11:27

I have Delphi 2007 code that looks like this:

procedure WriteString(Stream: TFileStream; var SourceBuffer: PChar; s: string);
begin
  StrPCopy(SourceBuffer,s);
          


        
相关标签:
2条回答
  • 2021-02-07 12:03

    Delphi 2010 has a nice solution for this, documented here:

    http://docwiki.embarcadero.com/CodeExamples/en/StreamStrRdWr_%28Delphi%29

    var
      Writer: TStreamWriter;
    ...
    
      { Create a new stream writer directly. }
      Writer := TStreamWriter.Create('MyFile.txt', false, TEncoding.UTF8);
      Writer.Write('Some Text');
    
      { Close and free the writer. }
      Writer.Free();
    
    0 讨论(0)
  • 2021-02-07 12:12

    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.

    0 讨论(0)
提交回复
热议问题