Reading and writing a file to and from a string

This article inroduces two handy functions for reading the contens of a file in a string and writing a string to a file.

Reading a file into a string

Perhaps the easiest way to read a file into a string is using the LoadFromFile method of a TStringList object and then accessing its Text property:



uses SysUtils, Classes;



  function LoadFile(const FileName: TFileName): string;

  begin

    with TStringList.Create do

      try

        LoadFromFile(FileName);

        Result := Text;

      finally

        Free;

      end;

  end;




However, this way of doing things is inefficient, since LoadFromFile loads the file and parses it to separate the lines, and then when we use the Text property, an internal method is called to produce a string joining the lines, so this double job is done for nothing, plus we end up using more than the double of the memory storage we actually need (until we free the TStringList object).



A better way

A better approach could be using a TFileStream object (or the old Assign, Reset, Read and Close procedures) to directly read the contents of a file into a string. Here is the same function using TFileStream that returns the content of the file whose name is passed as parameter:



uses SysUtils, Classes;



  function LoadFile(const FileName: TFileName): string;

  begin

    with TFileStream.Create(FileName,

      fmOpenRead or fmShareDenyWrite) do begin

      try

        SetLength(Result, Size);

        Read(Pointer(Result)^, Stream.Size);

      except

        Result := ''; // Deallocates memory

        Free;

        raise;

      end;

      Free;

    end;

  end;




Writing a file from a string

If we needed to save the contents of string back to disk, we can use the following procedure:



uses SysUtils, Classes;



  procedure SaveFile(const FileName: TFileName;

                     const content: string);

  begin

    with TFileStream.Create(FileName, fmCreate) do

      try

        Write(Pointer(content)^, Length(content));

      finally

        Free;

      end;

  end;

 

Share this article!

Follow us!

Find more helpful articles: