CSC 272 - Software II: Principles of Programming Languages
Dr. R. M. Siegfried
A Pascal program to read a text file
PROGRAM ReadFile;
{ Comments are enclosed in braces or in (* and *) }
{ Braces are more commonly used }
{ Constants, if they are declared go at the top }
CONST
FileNameLength = 20;
ArrayLength = 10;
{ Type declarations go next }
TYPE
{*************************************************}
{* Although types do not have to be declared in *}
{* order to declare string variables or arrays *}
{* it is considered good style. *}
{*************************************************}
FileNameType = String[FileNameLength];
ArrayType = ARRAY[1..ArrayLength] OF Integer;
VAR
{**************************************************}
{* Variable declarations go next. Procedure *}
{* declarations go afterward, if there are any. *}
{**************************************************}
FileName : FileNameType;
InputFile : Text; { A text file }
Vector : ArrayType;
i, VectorLen : Integer;
BEGIN
{ Get the file name and open it }
Write('Enter file name ?');
ReadLn(FileName);
{ Associate the file with the DOS name }
Assign(InputFile, FileName);
{ Open it for input }
Reset(InputFile);
VectorLen := 1; { Assignment statement }
WHILE NOT Eof(Inputfile) DO
BEGIN
{******************************************}
{* To use a ReadLn to read a file, *}
{* the file name goes first in the list *}
{******************************************}
ReadLn(InputFile, Vector[VectorLen]);
VectorLen := VectorLen + 1
END; { while not eof }
VectorLen := VectorLen - 1;
{*********************************************}
{* WriteLn stands for "write line" - there *}
{* is a carriage return added at the end *}
{*********************************************}
FOR i := 1 TO VectorLen
DO WriteLn('Vector[', i, '] = ', Vector[i]);
END. { ReadFile }
[Back to the Pascal Program Index]