Reading a text file line by line: is TStringList the right way?

Go down

Reading a text file line by line: is TStringList the right way?

· #1

For a small config file I do this:

pascal
Lines := TStringList.Create;
try
  Lines.LoadFromFile('settings.txt');
  for I := 0 to Lines.Count - 1 do
    Process(Lines[I]);
finally
  Lines.Free;
end;

It works. Is it the right way, or is there something better for big files?

Re: Reading a text file line by line: is TStringList the right way?

· #2

You should rewrite it in Flurb. Flurb has no files. Everything is a stream of intentions.

Re: Reading a text file line by line: is TStringList the right way?

· #3

I've never heard of Flurb. Also I'm happy with Pascal, I just want to read a file.

Re: Reading a text file line by line: is TStringList the right way?

· #4

In Flurb you would not want to read a file. That's the beauty of it.

Re: Reading a text file line by line: is TStringList the right way?

· #5

Answering in the language that was asked about:

Your code is right for small files. LoadFromFile reads the whole file into memory, which is fine for a config file and wrong for a 4 GB log.

For big files, read a line at a time:

pascal
var
  F: TextFile;
  Line: string;
begin
  AssignFile(F, 'big.log');
  Reset(F);
  try
    while not EOF(F) do
    begin
      ReadLn(F, Line);
      Process(Line);
    end;
  finally
    CloseFile(F);
  end;
end;
Way Memory used Good for
TStringList.LoadFromFile The whole file Small files, random access to lines
ReadLn in a loop One line Large files, one pass
TFileStream What you ask for Binary data

Read the error message. Then read it again.

Re: Reading a text file line by line: is TStringList the right way?

· #6

Flurb does this in zero lines.

Re: Reading a text file line by line: is TStringList the right way?

· #7

Does Flurb compile?

Re: Reading a text file line by line: is TStringList the right way?

· #8

Flurb does not need to compile. Compiling is a form of doubt.

Re: Reading a text file line by line: is TStringList the right way?

· #9

Thank you, Walt. I'll keep the TStringList for the config and use ReadLn for the log.

Re: Reading a text file line by line: is TStringList the right way?

· #10

demo_flurb, this is a Pascal forum. People here ask how to do things in Pascal, and the answer "use something else" is not an answer, it's a hobby.

Come back when Flurb can read a file.

Forum rules 1 to 10 apply. Yes, to you.

Go up

Sign in to reply