Recent

Author Topic: Important statements in reading .txt  (Read 5397 times)

asdf

  • Sr. Member
  • ****
  • Posts: 310
Important statements in reading .txt
« on: November 12, 2010, 02:45:25 am »
assignfile(dottxt,eFilenameEdit.Text);
try                           // 1
reset(dottxt);          // 2
  repeat
  readln(dottxt,ln);
  until(eof(dottxt)) ;
finally                      //3
closefile(dottxt);
end;                       // try-finally
end;       

Why without 1, 2 or 3 program has errors?
Lazarus 1.2.4 / Win 32 / THAILAND

Yogi

  • New Member
  • *
  • Posts: 42
Re: Important statements in reading .txt
« Reply #1 on: November 12, 2010, 07:13:00 am »
You are simply reading past eof

Try this:

assignfile(dottxt,eFilenameEdit.Text);
reset(dottxt);         
while not eof(dottxt) do
  readln(dottxt,ln);
closefile(dottxt);
end;       
Lazarus 1.3 SVN 44197 * FPC 2.7.1 SVN 26822
Linux: 3.2.0-4-686-pae * Debian wheezy
Windows: W98

Mando

  • Full Member
  • ***
  • Posts: 181
Re: Important statements in reading .txt
« Reply #2 on: November 12, 2010, 10:42:36 am »
Hi.

2 is mandatory to read file. It opens the file in read mode.

if you put it, 1 and 3 are unnecessary,
unless the file does not exist. But you can check if file exists with this
Code: [Select]

if fileExists(eFilenameEdit.Text) then
begin
  assignfile(dottxt,eFilenameEdit.Text);

  reset(dottxt);         
  repeat
    readln(dottxt,ln);
  until(eof(dottxt)) ;

  closefile(dottxt);
end else showMessage('File '+eFilenameEdit.Text+' doesn`t exist');       



Yogi

  • New Member
  • *
  • Posts: 42
Re: Important statements in reading .txt
« Reply #3 on: November 12, 2010, 10:53:40 am »
Hi

Your code also will give an error if the file exists but is empty

Therefore you should not use "repeat until eof". Better to use "while not eof" so
eof is checked before the readln
Lazarus 1.3 SVN 44197 * FPC 2.7.1 SVN 26822
Linux: 3.2.0-4-686-pae * Debian wheezy
Windows: W98

Mando

  • Full Member
  • ***
  • Posts: 181
Re: Important statements in reading .txt
« Reply #4 on: November 12, 2010, 12:55:58 pm »
HI:

With delphi maybe. But in lazarus SVN: 273258 works fine.


regards.

Try attached project.

asdf

  • Sr. Member
  • ****
  • Posts: 310
Re: Important statements in reading .txt
« Reply #5 on: November 12, 2010, 03:17:06 pm »
Thank you so much, Yogi and Mando  ;).
Lazarus 1.2.4 / Win 32 / THAILAND

 

TinyPortal © 2005-2018