Home Up Contents Search

Disc Files - Text

Text files are disc files consisting of lines of ASCII characters. Unlike memory-based Pascal data structures, text files are relatively permanent. Also, text files have no predefined length; they can be as long as your disc space permits. Text files are represented by variables of predefined type text. For example:

var MyFile : text;

Once a little setup work has been performed, you can read a text file as easily as reading the keyboard, and write to it as though you were writing to the screen. The same Writeln/Readln procedures are used, with the name of the file preceding the data to output in the call. For example:

Write('Hello');

sends 'Hello' to the screen, and:

Write(MyFile, 'Hello');

sends 'Hello' to the end of text file MyFile.

The Assign procedure makes a connection between a Pascal variable of type Text and the MS-DOS file name you want the file to have. Use the Reset procedure to prepare to read a text file; use Rewrite to create a new, empty text file in preparation for writing to it. Call Close when you're through working with a file.

Text files are sequential; that is, they must be accessed in order. This is in contrast to typed (random-access) files in which any part of the file can be accessed in any order.


program MakeATextFile;
var TheFile: Text;
begin

Assign(TheFile,'ADDRESS.TXT');
Rewrite(TheFile);
{ create a new, empty file and prepare to write to it }
Writeln(TheFile,'College of the South West');
Writeln(TheFile,'Timbury Street');
Writeln(TheFile,'ROMA 4455');
Close(TheFile);

end. { MakeATextFile }




program ReadATextFile;
var

TheFile: Text;
S:
String;

begin

Assign(TheFile,'ADDRESS.TXT');
Reset(TheFile);
{ prepare to read an existing file }
while not EOF(TheFile) do
begin

Readln(TheFile,S); { read from the file }
Writeln(S);
{ and write to the screen }

end;
Close(TheFile);

end. { ReadATextFile }

 
Previous Next
Send mail to ljschwerin@hotmail.com with questions or comments about this web site.

Copyright © 1999-2002 Leon Schwerin
Last modified: 26 March 2000
1