• Homework
  • Thirds
  • Upper Thirds
  • Fourth
  • Divisions
    • ICT
    • Computer Science
  • Fifth
  • Lower Sixth
  • Upper Sixth
    • Upper Sixth Theory
  • Blog
  • Careers
  • Unity
  • Networking
computinglesson.com

Reading and writing text files

Text files are the 'lowest common denominator' of all computer files.  They can't contain formatting information such as fonts, bold or underline, instead they just contain ASCII representation of text characters.

Steps to open and read a text file in Delphi

First, make sure the file is there and in a location that you can access it.  It should be possible to read a text file from the directory in which your program is running, but this isn't easy.  Better to give it a full path like the path name shown on the right:

  • Create a Textfile variable
  • 'Assign' the textfile variable to the actual file name
  • Use 'reset' to open the file for reading
  • Read a line at a time with readln(filevariable,stringtoputitin)
  • Check for EOF(filevariable) to check for the end
  • Close the file when you're done

Errors that you might encounter

I/O 103 - File not found - have you got the name right?
I/O 104 - File not open for input - Have you 'Assigned' it?
I/O 32 - File in use by another process - Is it open somewhere else?
uses
  System.SysUtils;

var poem : Textfile;
var lines : Array[0..100] of String;
var counter : integer;
var i : integer;

begin
  assignFile(poem,'N:\adelphi\poem\larkin.txt');
  reset(poem);
  counter := 0;
  while not EOF(poem) do
  begin
      write('.');
      counter := counter + 1;
      readln(poem,lines[counter]);
  end;
  writeln('Complete');
  for i := 1 to counter do
  begin
    writeln(lines[i]);
    sleep(500);
  end;
  readln;

end.

Powered by Create your own unique website with customizable templates.