Question

I am having problems with the following code:

var l :string;
var f:Textfile;
begin

  assignfile(f,'c:\test\file.txt');
  reset(f);
  while not eof(f) do
  readln(f,l);
  closefile(f);

  showmessage(l);

My problem is that the showmessage is returning nothing ... it's empty and the text file is not empty.

Why is this happening?

Was it helpful?

Solution 2

You read each new line in the same variable, thereby overwriting the last line with a new line. If the last read returns an empty string (or a string with just spaces or an enter), your message box will seem empty. And even if it were not empty, it would show only the last line, not the whole file.

Use l as a buffer. After each read, append it to another string:

var l: string;
var t: string;
var f: Textfile;
begin
  t := '';
  assignfile(f, 'c:\test\file.txt');
  reset(f);
  while not eof(f) do
  begin
    readln(f, l);
    t := t + l;
  end;
  closefile(f);

  showmessage(t);

For large files it is more efficient to use a String Builder instead of concatting everything to the same string, because t will be reallocated on each iteration.

Alternatively, use a TStringList or a TFileStream to read files. Using a TFileStream, you can read the whole file at once into a string. The TStringList has the advantage that it parses the file and makes each line an item in the stringlist.

But with those solutions, you are going to read the whole file into memory. If you can process it line by line, do the processing inside the loop.

OTHER TIPS

In addition to what has already been said:

Nobody uses lowlevel file routines these days. There are at least two much better approaches. The first involves streams, the second a TStringList:

var sl : TStringList;
begin
  sl := TStringList.Create;
  try
    sl.LoadFromFile('c:\your\file.txt');
    ShowMessage(sl.Text);
  finally
    sl.Free;
  end;
end;

Disclaimer: code not tested

The line

Readln(f, l)

puts the current line of f into the string l. Hence it will replace the previous line, so at the end, l will only contain the last line of the file. Maybe the last line is empty?

Most likely the last line of your file is empty.

You may want to try the following to see the difference:

while not eof(f) do
begin
  readln(f,l);
  showmessage(l);
end;
closefile(f);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top