DELPHI: Text files
 

A FILE is a data structure that can be stored permanently on a secondary storage medium.

A data structure…
• is a set of related data items;
• saved with one name;
• and organised in such a way that the individual data items can be accessed.

A text file contains only ASCII (American Standard Code of Information Interchange) characters and therefore no formatting or graphics.

TIP: Create text files to be used in Delphi can be created in Delphi (File > New > Text), in Notepad or in MS Word (remember to select 'Plain text (*.txt)' when saving). Most often the extension TXT is used to indicate that it is a text file - but you could use an extension DAT or any other available one for your programs.


Use a memo box and two buttons (one to save and one to open with):

Take note of the coding:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Lines.SaveToFile('c:\test.txt');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Memo1.Lines.LoadFromFile('c:\test.txt');
end;

These procedures do all the work for you – only the file name needs to be specified.

You can use the SaveDialog and OpenDialog to let the user decide on the file name. Look for the Save and Open Dialogs under the ‘Dialog’ tab on the Component palette.

These components are only visible during edit mode:




Method 1
Look for the Save and Open Dialogs under the ‘Dialog’ tab on the Component palette.
These components are only visible during edit mode:

The coding is then changed to:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if SaveDialog1.Execute then
  begin
    Memo1.Lines.SaveToFile(SaveDialog1.FileName);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
  begin
    Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
  end;
end;


Method 2
Use a RichEdit and two buttons (one to save and one to open with):

Procedures used:
• AssignFile – assigns file name to file variable
• Reset – Set focus to start of file; file ready to be read
• Readln – Reads line of file and stores it in a string variable
• CloseFile – closes file for reading or writing
• Append – opens up already created file and places focus at the end of the file to add new text
• Rewrite – creates new file and sets focus to start of file

The RESET, APPEND, REWRITE and CLOSEFILE procedures are essential because files need to be OPENED before use and CLOSED after use.

procedure TForm1.Button1Click(Sender: TObject);
var
  fFile : TextFile;
  sLine : String;
  iCount : integer;

begin
  AssignFile(fFile, 'c:\test.txt');
  Rewrite(fFile);
  FOR iCount := 0 to RichEdit1.Lines.Count-1 DO
  BEGIN
    sLine := RichEdit1.Lines[iCount];
    Writeln(fFile, sLine);
  END;
  CloseFile(fFile);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  fFile : TextFile;
  sLine : String;

begin
  RichEdit1.clear;
  AssignFile(fFile, 'c:\test.txt');
  Reset(fFile);
  WHILE NOT Eof(fFile) DO
  BEGIN
    Readln(fFile, sLine);
    RichEdit1.Lines.Add(sLine);
  END;
  CloseFile(fFile);
end;

WHILE NOT eof(fFile) DO means that while the end of the file is not reached (reading from the start to the end) the instructions below must be followed

Add coding to your program to check whether a file exists or not – this way I/O errors can be avoided.

More user friendly:

procedure TForm1.Button1Click(Sender: TObject);
var
  fFile : TextFile;
  sLine : String;
  iCount : integer;
begin
  AssignFile(fFile, 'c:\test.txt');
  IF FileExists('c:\test.txt') <> true THEN       
    Rewrite(fFile)                                
  ELSE
    Append(fFile);                                
  FOR iCount := 0 to RichEdit1.Lines.Count-1 DO
  BEGIN
    sLine := RichEdit1.Lines[iCount];
    Writeln(fFile, sLine);
  END;
  CloseFile(fFile);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  fFile : TextFile;
  sLine : String;

begin
  RichEdit1.clear;
  IF FileExists('c:\test.txt') <> true THEN
  BEGIN
    MessageDlg('File does not exist', mtError,[mbOK],0);
    Exit;
  END;
  AssignFile(fFile, 'c:\test.txt');
  Reset(fFile);
  WHILE NOT eof(fFile) DO
  BEGIN
    Readln(fFile, sLine);
    RichEdit1.Lines.Add(sLine);
  END;
  CloseFile(fFile);
end;


Printing
To print a text file, add the following:
• A button
• A print dialog
• Add ‘Printers’ to your Uses declaration at the top of your program.

Coding for Print button:

procedure TForm1.Button3Click(Sender: TObject);
var
  iCount: Integer;
  PrintText: TextFile;
begin
  if PrintDialog1.Execute then
  begin
    AssignPrn(PrintText);
    Rewrite(PrintText);
    Printer.Canvas.Font := RichEdit1.Font;
    FOR iCount := 0 to Richedit1.Lines.Count-1 DO
      Writeln(PrintText, RichEdit1.Lines[iCount]);
    CloseFile(PrintText)
  end;
end;


EXAMPLE ASSIGNMENT
Use the coding provided and create a basic word processing program that can create, save, open and print text files using the relevant dialogs. Make it as user friendly as possible.

Assessment rubric

Text file components used correctly and solution correct.
Good form layout. Very user friendly (error handling and instructions).
4
Components/structures used incorrectly. Only partially solved.
Form layout – needs attention. Partially user friendly.
3
Components/structures partly used. Solution incorrect. 2
Incorrect components used. No solution. Very little coding. 1

Further reference – see:
• Enjoy Delphi (Part 2) – p.1-13
• http://delphi.about.com/od/fileio/a/ascii_textfile.htm
• http://www.delphibasics.co.uk/Article.asp?Name=Files
• http://www.delphicorner.f9.co.uk/articles/misc2.htm
 

Return to Delphi resources index




Return to Home Page

© JAK Olivier (2008)

Website: http://www.jako.nom.za/
E-mail: olivier@teachitza.com