Reputation: 51
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?)
Upvotes: 3
Views: 11080
Reputation: 612844
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;
Upvotes: 8
Reputation: 136391
Starting with Delphi XE 2010 you can use the IOUtils.TFile.ReadAllLines
function to read the content of text file in a single line of code.
class function ReadAllLines(const Path: string): TStringDynArray;
class function ReadAllLines(const Path: string; const Encoding: TEncoding): TStringDynArray; overload; static;
Upvotes: 8