Posted by webmaster Guido on May 16, 2008
In Reply to Garbage written to a TFileStream posted by RussCAp12602 on
May 10, 2008
: I am trying to write the text from a RichEdit.Lines.GetText to a TFileStream. It works, but the result is a file full of gibberish.
: Here's sort of what I have:
: TS: TFileStream;
: Tx: String;
: i: Integer;
: TS := TFileStream.Create('text.txt', fmCreate);
: Tx := reEdit.Lines.GetText;
: i := Length(Tx);
: TS.Write(Tx, i);
: The proper number of bytes (i) are written to the file. However, the actual data written is pure garbage that bears no similarity to the contents of Tx that I can determine.
: What am I doing incorrectly?
Seems to me that what you want to accomplish is writing the "plain" text of the RichEdit to a text file, without the formatting codes. You can do this with the following source code:
RichEdit1.PlainText := True; RichEdit1.Lines.SaveToFile('retext.txt'); RichEdit1.PlainText := False;
If you don't set PlainText to True, the formatting codes are also saved in the text file.
Here's some code for getting the contents of a text file into a file-stream, if for example you want to modify it and write it back later on:
var FS: TFileStream; begin FS := TFileStream.Create('retext.txt', fmOpenRead); // Do something with the file stream: ShowMessage('Size of file stream: ' + IntToStr(FS.Size)); // Do some more processing: ... FS.Free; end;