//from http://kingron.myetang.com/zsfunc0d.htm (*// 标题:充分利用pascal字符串类型 说明:和PChar不同,string可以保存#0字符在其中;示例文件、内存流字符串之间转换 设计:Zswang 日期:2002-01-25 支持:wjhu111@21cn.com //*) ///////Begin Source function StringTofile(mString: string; mfilename: Tfilename): Boolean; { 返回字符串保存到文件是否成功 } var vfileChar: file of Char; I: Integer; begin {$I-} Assignfile(vfileChar,mfilename); Rewrite(vfileChar); for I := 1 to Length(mString) do Write(vfileChar,mString[I]); Closefile(vfileChar); {$I+} Result := (IOResult = 0) and (mfilename <> ''); end; { StringTofile } function fileToString(mfilename: Tfilename): string; { 返回从文件载入字符串 } var vfileChar: file of Char; vChar: Char; begin Result := ''; {$I-} Assignfile(vfileChar,mfilename); reset(vfileChar); while not Eof(vfileChar) do begin Read(vfileChar,vChar); Result := Result + vChar; end; Closefile(vfileChar); {$I+} end; { fileToString } function StreamToString(mStream: TStream): string; { 将内存流转换成字符串 } var I: Integer; begin Result := ''; if not Assigned(mStream) then Exit; SetLength(Result,mStream.Size); for I := 0 to Pred(mStream.Size) do try mStream.position := I; mStream.Read(Result[Succ(I)],1); except Result := ''; end; end; { StreamToString } function StringToStream(mString: string; mStream: TStream): Boolean; { 返回将字符串保存到内存流是否成功 } var I: Integer; begin Result := True; try mStream.Size := 0; mStream.position := 0; for I := 1 to Length(mString) do mStream.Write(mString[I],1); except Result := False; end; end; { StringToStream } ///////End Source ///////Begin Demo procedure TForm1.button1Click(Sender: TObject); var vMemoryStream: TMemoryStream; begin Memo1.Text := fileToString('C:\windows\Desktop.txt'); vMemoryStream := TMemoryStream.Create; try Memo1.lines.SavetoStream(vMemoryStream); Memo2.Text := StreamToString(vMemoryStream); finally vMemoryStream.Free; end; end; procedure TForm1.button2Click(Sender: TObject); var vMemoryStream: TMemoryStream; begin StringTofile(Memo2.Text,'C:\windows\Desktop.txt'); vMemoryStream := TMemoryStream.Create; try StringToStream(Memo2.Text,vMemoryStream); vMemoryStream.position := 0; Memo1.lines.LoadFromStream(vMemoryStream); finally vMemoryStream.Free; end; end; ///////End Demo总结
以上是内存溢出为你收集整理的delphi 怎么将一个流转换成字符串?全部内容,希望文章能够帮你解决delphi 怎么将一个流转换成字符串?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)