Reading and writing text files.
Language(s):Delphi
Category(s):File IO

Shows how to read and write to text files.

{
  This sample code is presented as is.
  Although every reasonable effort has been
  made to insure the soundness of the example
  below, Idioma Software inc. makes no warranty
  of any kind with regard to this program sample
  either implicitly or explicitly.

  This program example may be freely distributed for the
  use of writing computer programs only. Any other use of
  this material requires written permission from Idioma Software inc.

  (c) 1997 Idioma Software inc. All rights reserved.
}

{
   This example shows how to do IO using records.
}
Procedure TextIO;
{Author Jon Vote 10/97}
{Uses SysUtils, Dialogs}

const FILE_NAME = 'texttest.tmp';

var IORec      : string;         {Record Varibale}
    f          : Textfile; {File variable}
    SearchRec  : TSearchRec;     {Used with FindFirst}
    i          : integer;
begin

assignfile(f, FILE_NAME);

{create the file if it doesn't exist, otherwise erase it}
if FindFirst(FILE_NAME, 0, SearchRec) = 0 then
  Erase(f);

Rewrite(f);
Reset(f);

FindClose(SearchRec);  {Always do this after FindFirst, FindNext}
Append(f);

for i := 1 to 10 do begin
  IORec := 'Record number ' + IntToStr(i);
  writeln(f, IORec);
end; {for}

{Read the values back}
reset(f);
While not eof(f) do begin
  readln(f, IORec);
  ShowMessage (IORec);
end; {While}

{Add a record to the end}
Append(f);
IORec := 'This is the last record.';
writeln(f, IORec);

{Read the values back}
reset(f);
While not eof(f) do begin
  readln(f, IORec);
  ShowMessage (IORec);
end; {While}

{Delete the file}
Erase(f);

CloseFile(f);

end; {TextIO}

This article has been viewed 4613 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.