Read a text file in a table

advertisements

How would I go about reading a text file from a file on disk into an array in memory?

Also, I noticed using ReadLn only shows the first line (seems kind of obvious, since it is ReadLn, but how would I go about reading the whole text document?)


function ReadFile(const FileName: string): string;
var
  Strings: TStringList;
begin
  Strings := TStringList.Create;
  try
    Strings.LoadFromFile(FileName);
    Result := Strings.Text;
  finally
    Strings.Free;
  end;
end;

That returns the file's contents in a string which can be indexed and so could be considered to be an array.

Or perhaps you want an array of strings rather than an array of characters, in which case it's easiest just to use the string list directly:

var
  Strings: TStringList;
...
  Strings := TStringList.Create;
  try
    Strings.LoadFromFile(FileName);
    //can now access Strings[0], Strings[1], ..., Strings[Strings.Count-1]
  finally
    Strings.Free;
  end;