CSC 272 - Software II: Principles of Programming Languages
Dr. R. M. Siegfried
A Pascal program to write a text file
PROGRAM WriteFileProgram;
CONST
FileNameLength = 20;
ArrayLength = 10;
TYPE
{*************************************************}
{* We need to declare these types if we are *}
{* going to pass variables of these types as *}
{* parameters. *}
{*************************************************}
FileNameType = String[FileNameLength];
ArrayType = ARRAY[1..ArrayLength] OF Integer;
VAR
FileName : FileNameType;
OutputFile : Text;
Vector : ArrayType;
i, VectorLength : Integer;
PROCEDURE OpenFile(VAR OutputFile : Text);
BEGIN
{ Get the file name and open it }
Write('Enter file name ?');
ReadLn(FileName);
Assign(OutputFile, FileName);
{ Open it for output }
ReWrite(OutputFile)
END; { OpenFile }
PROCEDURE GetVector(VAR x : ArrayType; VAR n : Integer);
{*****************************************}
{* This procedure reads in the values *}
{* to be placed in the array *}
{*****************************************}
BEGIN
n := 0;
{******************************************}
{* REPEAT..UNTIL executes at least once *}
{* by placing the test at the end and it *}
{* must be the reverse of the WHILE *}
{* condition. *}
{******************************************}
REPEAT
n := n + 1;
Write('Enter a value ?');
ReadLn(x[n]);
writeln (x[n], ' ', n)
UNTIL (x[n] = 0) OR (n = 10);
IF x[n] = 0
THEN n := n - 1;
END; { GetVector }
PROCEDURE WriteFile(VAR OutputFile : Text;
x : ArrayType; n : Integer);
{ Write the data in a text file }
VAR i : Integer;
{***********************************}
{* This procedure is exclusively *}
{* available for WriteFile *}
{***********************************}
PROCEDURE CloseFile;
BEGIN
{ OutputFile is a global variable }
Close(OutputFile)
END; { CloseFile }
BEGIN { WriteFile }
FOR i := 1 TO n DO WriteLn(OutputFile, x[i]);
CloseFile
END; { WriteFile }
BEGIN { WriteFileProgram }
OpenFile(OutputFile);
GetVector(Vector, VectorLength);
WriteFile(OutputFile, Vector, VectorLength)
END. { WriteFileProgram }
[Back to the Pascal Program Index]