How to properly work with FileRead, FileWrite, buffers (or with TFileStream).
I need to read a whole text file to a String, then to write back a String to this file (replace it with a new string).
TStringList
is what you want if you need to deal with the file on a per-line basis.
If you just want to treat it as a single string blob then there is TStringStream
.
Stream := TStringStream.Create('', TEncoding.UTF8);
Try
Stream.LoadFromFile('c:\desktop\in.txt');
ShowMessage(Stream.DataString);
Stream.Clear;
Stream.WriteString('Greetings earthlings!');
Stream.SaveToFile('c:\desktop\out.txt');
Finally
Stream.Free;
End;
The simplest, most fool-proof way to read a file into a string is to use a TStringList like so:
sl := TStringList.Create;
try
sl.LoadFromFile('C:\myfile.txt');
//String can be read and modified using the Text property:
oldString := sl.Text;
sl.Text := 'foo bar';
//Text can be written back to the file using:
sl.WriteToFile('C:\myfile.txt');
finally
sl.Free;
end;
As has been noted in the comments below your question, this could end up transforming line breaks within your string - so depending on what you're trying to read / do, you will need to look out for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With