Programming in PASCAL Module 08 - Files _Serial_ by nuhman10

VIEWS: 6 PAGES: 9

									Programming in Pascal - 8



Programming in PASCAL                            Module 08 – Files (Serial)

Contents
Introduction
Text Files
Typed Files


Introduction
In the many examples that have been considered so far any data that has been entered has
been lost once the programs have completed. Data can be preserved for future use by
saving it in files on the computer’s disk drive. A file, in this context, can be defined as a
sequence of elements of the same type.

Pascal supports three different types of files: Text, typed an un-typed files. This module
will look at the first two.

Text Files
Text files are files that contain a sequence of characters arranged into lines that are
terminated by an end-of-line (EOLN) character. A text file can be created and read in
simple text editor such as MS Notepad or JED.

The steps in reading and writing files are:
Declare a file variable                           AFile : Text;
Associate the file path with the file variable    Assign(AFile,’testfile.txt’);
To open an existing file                          Reset(AFile);
To create a new file                              Rewrite(AFile);
To open a file for appending data                 Append(AFile);
To read from the file                             Read(AFile, variablelist);
To write to the file                              Write(AFile, variablelist);
To close the file                                 Close(AFile);

The first example illustrates how text can be read from a file and displayed on the screen.
To test the program you must first create a file called ‘testfile.txt’ in the same folder as the
program using MS Notepad. Enter some sentences then run the program.
// Ex 8.1 Program to read a text file and display on screen
program NineOne;

uses
  SysUtils, win32crt;

var
  AFile : Text;    //Declare the           file variable
  ALine : String;
begin
  //
  assign(AFile, 'testfile.txt');           //Assign file variable to actual file
  reset(AFile);                            //Open file for read/write
  while not EoF(AFile) do                  //Keep reading lines until
                                           //the end of file is reached
  begin



                                                                                                1
Programming in Pascal - 8


     readln(AFile, ALine);                //Read each line from file
     writeln(ALine);                      //Display on screen
  end;
  close(Afile);                           //Close the file
end.

The second example show how text entered at the keyboard can be written to a text file. It
illustrates the use of EOF and EOLN. When you have run the program and entered some
text open the file ‘testfile2.txt’ in MS Notepad to check that it is the same as what you
typed including the line structure.
//Ex 8.2 Program to write keyboard text to a file
program NineTwo;

uses
  SysUtils, win32crt;

var
  AFile : Text;             //Declare the file variable
  ch : char;

begin
  //
  assign(AFile, 'testfile2.txt'); //Assign file variable to actual file
  rewrite(AFile);                 //Create new file
  writeln('Enter your text - Press CTRL/Z to finish');
  checkEOF:=True;                 //Need this when using win32crt
  while not EOF do                //EOF true when you type CTRL/Z EOF
  begin                           //refers to the end of what you type
     while not EOLN do
     begin
       read(ch);
       write(AFile,ch);
     end;
  readln; writeln(Afile);         //Write the EOLN characters to the file
  end;
  close(AFile)
end.

In most applications it is usually necessary to store data until the next time it is required.
This is done by storing the data in a file. The third example shows how structured data in
the form or records can be written to a text file. Run the program and enter two or three
records. View the resulting file ‘mydata.dat’ in Notepad. You will see that the data for
each record is held in one line but that the fields in each record are not separated in any
way. This structure of the file would make it difficult to read the records back as there is
no simple way of separating the individual fields. One way of doing this would be to
separate the fields by writing an end-of-field character, such as a comma, between the
fields. This approach is the basis of CSV (comma separated value) files that are commonly
used to transfer data between different applications.




                                                                                            2
Programming in Pascal - 8


//Ex 8.3 Writing records to a text file (1)
program NineThree;

uses
  SysUtils,
  win32crt;

var
  AFile : Text;
  ans   : char;
  ASurname : string[25];
  AForename : string[20];
  APhone : string[14];

begin
  Assign(AFile,'mydata.dat');
  Rewrite(AFile);

  writeln('Phone Book');
  ans:='Y';
  while ans in ['Y','y'] do
  begin
    write('Enter Surname:      '); readln(ASurname);
    write('Enter Forename:     '); readln(AForename);
    write('Enter Phone Number: '); readln(APhone);

     //Write all fields in record on one line
     writeln(Afile,ASurname,AForename,APhone);
     writeln;
     write('Another record? enter Y or N: ');
     readln(ans);
  end;
  close(AFile);
end.

An alterative way of writing the records is to simply write each field on a new line. This is
done in the fourth example.
//Ex 8.4 Writing records to a text file (2)
program NineFour;

uses
  SysUtils, win32crt;

var
  AFile : Text;
  ans   : char;
  ASurname : string[25];
  AForename : string[20];
  APhone : string[14];

begin
  Assign(AFile,'mydata.dat');
  Rewrite(AFile);

  writeln('Phone Book');
  ans:='Y';
  while ans in ['Y','y'] do
  begin
    write('Enter Surname:              '); readln(ASurname);
    write('Enter Forename:             '); readln(AForename);



                                                                                            3
Programming in Pascal - 8


     write('Enter Phone Number: '); readln(APhone);

     //Write each field on a new line
     writeln(Afile,ASurname);
     writeln(Afile,AForename);
     writeln(Afile,APhone);

     writeln;
     write('Another record? enter Y or N: ');
     readln(ans);
  end;
  close(AFile);
end.

Writing the fields on separate lines makes reading the records back from the file much
easier as is shown in the fifth example.
//Ex 8.5 Reading simple records from a text file
program NineFive;

uses
  SysUtils,
  win32crt;

var
  AFile : Text;
  ans   : char;
  ASurname : string[25];
  AForename : string[20];
  APhone : string[14];

begin
  Assign(AFile,'mydata.dat');
  Reset(AFile);

  writeln('Phone Book');
  while not EOF(AFile) do
  begin
    readln(AFile,ASurname);
    readln(AFile,AForename);
    readln(AFile,APhone);

     writeln('Surname:      ',ASurname);
     writeln('Forename:     ',AForename);
     writeln('Phone Number: ',APhone);

     writeln;
  end;
  close(AFile);
end.

In serial access files data can only added at the end of the file. The append command
shown in the next example opens the file for reading and writing and places the internal
record pointer at the end of the file. New records will then be written at the end of the file.




                                                                                              4
Programming in Pascal - 8


//Ex 8.6 Adding (appending) data to existing file
program NineSix;

uses
  SysUtils,
  win32crt;

var
  AFile : Text;
  ans   : char;
  ASurname : string[25];
  AForename : string[20];
  APhone : string[14];

begin
  Assign(AFile,'mydata.dat');
  Append(AFile);              //Open file and place record pointer at end
                              //ready to append data
  writeln('Phone Book');
  writeln('Appending records to file');
  ans:='Y';
  while ans in ['Y','y'] do
  begin
    write('Enter Surname:       '); readln(ASurname);
    write('Enter Forename:      '); readln(AForename);
    write('Enter Phone Number: '); readln(APhone);

     writeln(Afile,ASurname);
     writeln(Afile,AForename);
     writeln(Afile,APhone);

     writeln;
     write('Another record? enter Y or N: ');
     readln(ans);
  end;
  close(AFile);
end.



Typed Files
Files can also be defined as containing records of a particular type. This is done by
declaring the file in the following way:
                           type-identifier = file of component-type;
The component type could be a simple data type like integer, real, array etc. or it could be
a user defined type like a record structure.

The following examples show how files of records could be written and read in this way.




                                                                                               5
Programming in Pascal - 8


Example 8.7 simply creates an empty phone file. The file is declare as a file of a user-
defined record type.
//Ex 8.7 Create an empty file
program NineSeven;

uses
  SysUtils,
  win32crt;

type
  APhoneRecordType = record
                       ASurname : string[25];
                       AForename : string[20];
                       APhone : string[14];
                     end;
  APhoneFileType = file of APhoneRecordType;

var
  AFile : APhoneFileType;

begin
  writeln('Phone Book');
  writeln('Creating empty file..');

  Assign(AFile,'mydata.dat');
  Rewrite(AFile);
  Close(AFile);

  writeln('File created.');
end.

Example 8.8 shows how records can be appended to the data file. Note that there is a
procedure MoveToEndOfFile that moves the record pointer to the end of the file ready for
appending records. This is because it is not possible to open a typed file using the Pascal
append command.
//Ex 8.8 Add/Append records to Phone file
program NineEight;

uses
  SysUtils,
  win32crt;

type
  APhoneRecordType = record
                       ASurname : string[25];
                       AForename : string[20];
                       APhone : string[14];
                     end;
  APhoneFileType = file of APhoneRecordType;

var
  APhoneFile : APhoneFileType;
  OnePhoneRecord : APhoneRecordType;
  ans : char;

procedure getPhoneRecord(var ARecord : APhoneRecordType);
begin
  with ARecord do begin
      write('Surname             : '); readln(ASurname);



                                                                                              6
Programming in Pascal - 8


         write('Forename                  : '); readln(AForename);
         write('Phone number              : '); readln(APhone);
  end;
end;

procedure writePhoneRecord(var F:APhoneFileType;
ARecord:APhoneRecordType);
begin
     write(F,ARecord);
end;

procedure MoveToEndOfFile(var F:APhoneFileType);
var
  ARecord:APhoneRecordType;

begin
  while not eof(F) do begin
    read(F,ARecord);
  end;

end;

begin
  writeln('Phone Book');
  writeln('----------');

  Assign(APhoneFile,'mydata.dat');
  Reset(APhoneFile);
  MoveToEndOfFile(APhoneFile);
  writeln('Enter a phone book record: ');
  ans:='Y';
  while ans in ['Y','y'] do
  begin
     getPhoneRecord(OnePhoneRecord);
     writePhoneRecord(APhoneFile,OnePhoneRecord);
     write('Another record? enter Y or N: ');
     readln(ans);
  end;
  Close(APhoneFile);
  writeln('File updated.');
end.

Example 8.9 displays the records in the file on the screen by reading the records serially
from the file.
//Ex 8.9 Read records from Phone file
program NineNine;

uses
  SysUtils,
  win32crt;

type
  APhoneRecordType = record
                       ASurname : string[25];
                       AForename : string[20];
                       APhone : string[14];
                     end;
  APhoneFileType = file of APhoneRecordType;

var



                                                                                             7
Programming in Pascal - 8


  APhoneFile : APhoneFileType;
  OnePhoneRecord : APhoneRecordType;
  ans : char;

procedure displayPhoneRecord(var ARecord : APhoneRecordType);
begin
  with ARecord do begin
       writeln('Surname            : ',ASurname);
       writeln('Forename           : ',AForename);
       writeln('Phone number       : ',APhone);
  end;
end;

procedure readPhoneRecord(var F:APhoneFileType; var
ARecord:APhoneRecordType);
begin
     read(F,ARecord);
end;

procedure MoveToEndOfFile(var F:APhoneFileType);
var
  ARecord:APhoneRecordType;

begin
  while not eof(F) do begin
     read(F,ARecord);
  end;
end;

begin
  writeln('Phone Book');
  writeln('----------');

  Assign(APhoneFile,'mydata.dat');
  Reset(APhoneFile);

  writeln('Reading records from file..');
  while not eof(APhoneFile) do
  begin
     readPhoneRecord(APhoneFile,OnePhoneRecord);
     displayPhoneRecord(OnePhoneRecord);
     writeln;
  end;
  Close(APhoneFile);
  writeln('File finished.');
end.

Q1. Combine the declarations from examples 9.7, 9.8 and 9.9 into a single program and
add a menu structure to control. The menu could include options to create a new file, add
a record, list the records.

Q2. Extend the phone book program to include an option to search for a phone record by
name. You will need to write a procedure called findPhoneRecord. It must be able to deal
with not being able to find the record and must return the position of the record in the file
as well as its contents.




                                                                                            8
Programming in Pascal - 8


Q3. Extend the phone book program by adding an option to delete a record from the file.
This will involve finding the record and then deleting by copying the file without the
deleted record.




                                                                                          9

								
To top