Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileOpen, FileRead, FileWrite

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).

like image 558
maxfax Avatar asked Jun 18 '11 17:06

maxfax


2 Answers

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;
like image 60
David Heffernan Avatar answered Oct 11 '22 15:10

David Heffernan


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.

like image 41
Steve Mayne Avatar answered Oct 11 '22 13:10

Steve Mayne