~ Introduction to Programming: Pascal ~

Session 9 - File Handling

<<  Back to Contents Page

Unit 10 – File Handling

 We have learned how to store information in variables for use during the execution of a program, to store temporary, or working, information.

 However, it is often necessary to store information more permanently, so that it can be accessed again, even after the program has finished, the computer switched off etc. – examples are Pascal source code files (.pas files), word-processed documents, spreadsheets, accounts data, booking information etc.

 A common way of storing this information is to make use of disk files – so we can write the information we wish to preserve to either a floppy disk, or a hard disk, or a network disk. Then later, we can read the information back into the program from the file to work on it some more.  

Declaring a File variable

 Files in Pascal are represented using a new variable type called a file. As integers are for whole numbers or Strings are for text, a file is for storing information about accessing a file.

 For example, to declare that you wish to use a file that will store text data, you could use:-

             var fileData : file of char;

 The file of char part specifies that the file will be written as text, or character-based information. The fileData part specifies the name of the variable.

 This is a very common form of file used in file processing, so Pascal has a short-hand version of declaring this type, called TEXT. You would declare it as follows:-

             var fileDate : TEXT;

Opening a file to write information

 In order to write information to a file, you need to perform the following steps:-

Type out the following program:-

program File1;

 

uses Wincrt;

 

const fileName = 'C:\TEMP\STUDENTS.TXT';

 

var outFile : TEXT;

    courseName, studentName : string;

 

begin

 

  clrScr;

  writeLn('What is the name of the course? ');

  readLn(courseName);

  writeLn;

  writeLn('Enter students for course, one per line.');

  writeLn('Enter a blank line to finish.');

 

  assign(outFile, fileName);

  rewrite(outFile);

 

  writeLn(outFile, 'Course is: ',courseName);

 

  repeat

    readln(studentName);

    if Length(studentName) > 0 then

      writeLn(outFile, studentName);

  until Length(studentName) = 0;

 

  close(outFile);

 

  writeLn('Students for course written to file');

  readKey;

 

end.

 The purpose of this program is to read a course title from the user, once only. A file is then opened, and the course title is written to the file.

A list of students, one per line, is taken from the user. Each is written to the file straight after they are typed.

When the user enters a blank line (i.e. the length of the studentName string is zero – Length(studentName)=0) the line is not written to the file, and the loop to get a list of students' names is terminated.

 So how do we achieve this?

 The outFile variable will hold the details of the Text file to be opened. A file can hold only one type of data – for example, a file of integer could be used to output a list of integer numbers to a file, but it could not then hold strings.

In order to specify which file is to be opened, the assign keyword is used, which takes two parameters (i.e. items that appear in brackets straight after the keyword) – the file variable, and the filename of the file that is to be used.

For example, assign(outFile, fileName) will write to the fileName variable ('c:\temp\students.txt') using the outFile file variable.

 To open the file, use the rewrite keyword with the file variable as a parameter  - e.g. rewrite(outFile).

 To write some text to the file, use a variation of the write or writeLn procedures, where the first parameter must be the file to write the text to. So instead of going to the screen, the data is written to the text file – e.g. to write the course name (as entered at the keyboard) to the outFile file (i.e. to the c:\temp\students.txt file):- writeLn(outFile, courseName).

 Finally, to close the file, once we have finished with it, we use the close procedure, passing the file variable again – e.g. close(outFile)

Exercise: Check file has written properly

 Try running the above program, and type out the following data:-

 Open the file using either notepad or Windows Explorerc:\temp\students.txt – and see if you can work out how the program produced the data in the text file. This also proves that your data has been written out properly.  

Exercise: Allow multiple courses to be written to the file

 Make an alteration to the program, so that if the user types out the word course, then another course is prompted for, and the following are output to the file:-

A list of students should then be prompted for, and another list of students can be entered into the system.

In this way, the user of the program can type in as many courses and lists of students as is required.

Hints

 You need two repeat…until loops, one inside the other. The first loop tests to see if the word course was entered, the second is the one already there:-

repeat

  { … get course and write it to the file }

  repeat

    { … get students and write them to the file }

  until (length(studentName)=0) or (studentName='course');

  if courseName='course' then writeLn(outFile);

until length(studentName)=0;

 You may like to write a message before the second loop begins to let the user know that not only does enter a blank line terminate writing to the file, but entering the word course lets them enter another course – e.g.

writeLn('Enter "course" for another course.');

  Additional Exercises 

 You may like to attempt these exercises when you have finished the rest of this text, if you find you have some spare time on your hands. You may wish to complete them when you get home, if you have the facilities available to you:-

 ·        Change the filename text to PRN: - this should tell Pascal to send the output not to a file, but instead to the printer. Note that the success of this depends on how the printer for your computer is set-up.

·        If you have the time, see if you can work out how to change the program to take a filename from the keyboard, and store the text to that file instead of the fixed constant.

·        Additionally, see if you can change the program to write different courses to different files – so the filename will have to be entered at the keyboard for each course. Careful that you open and close the file for each course.  

Opening a file to read information

 Once you have written some information to a file, it is useful to be able to read it back into your program again to make use of it.

The following program will take the student file that you created previously, read in the course name, and for each student, print out a certificate headed with the course name and the student name.

The program makes the assumption that you have only one course and one list of students in the file. You could assume that writing to the file called 'PRN:' will do the trick of writing to the printer. However, for the purposes of testing, we will save the results to a file in order to avoid wasting lots of paper!

Type it in and run it to see what happens:-

program File2;

 

const fileName = 'C:\TEMP\STUDENTS.TXT';

      reportName = 'C:\TEMP\REPORT.TXT';

var inFile, outFile : TEXT;

    courseName, studentName : string;

 

begin

 

  assign(inFile, fileName); reset(inFile);

  assign(outFile, reportName); rewrite(outFile);

 

  readLn(inFile, courseName);

  courseName:=copy(courseName,12,255);

 

  while not eof (inFile) do

  begin

    readLn(inFile,studentName);

    writeLn(outFile, 'CERTIFICATE OF COURSE ATTENDANCE');

    writeLn(outFile, '--------------------------------');

    writeLn(outFile);

    writeLn(outFile,'This certifies that ',studentName);

    write(outFile,'has completed the course: ');

    writeLn(outFile,courseName);

    writeLn(outFile); writeLn(outFile); writeLn(outFile);

    writeLn(outFile,'   Signed _________ (Facilitator)');

    writeLn(outFile);

    writeLn(outFile, '================================');

    writeLn(outFile); writeLn(outFile); writeLn(outFile);

  end;

  close(outFile); close(inFile);

 

end.

 

This program produces no screen output – its functionality is purely dealing in processing files. Note that this is a very common function in businesses – this type of program is commonly used to process data overnight.  

You can see that opening a file is a similar process to writing to a file. You use the assign procedure to assign a filename to read data from, and link that to a file variable.

Instead of using the rewrite procedure (which writes to the file), use the reset procedure, which effectively resets the file pointer to start reading from the beginning of the file.

To close the file once you have finished reading from it, use the close procedure as for writing to files.

Finally, to read lines of text from the file, use the readLn procedure, which reads a line of text from the text file, up to the end of the line. The parameters for readLn are the same as for reading text from the keyboard, except the first parameter should be the file variable – so the structure is similar to writeLn.

Exercise: Check report file has written properly

Try running the above program, and type out the following data:-

Open the file using either notepad or Windows Explorerc:\temp\report.txt – and see if you can work out how the program produced the data in the text file. This also proves that your data has been written out properly.

Exercise: Create a satisfaction survey for each student

Alter the program File2, so that it also creates a file called c:\temp\survey.txt and writes to it the following information for each student:-

COURSE SURVEY

-------------

 

Course: Course name

Name: Name of Student

 

 

Could you take a few moments to

complete this survey:-

 

[ ] Did you find the course useful?

[ ] Would you recommend it?

[ ] Should the tutor get a life?

 

Thank you for your time.

================================

 

 


Hint: You will need to create a new file variable (e.g. surveyFile : Text), assign it a new constant name, rewrite it to write to it, and use the WriteLn and Write commands to write to the file. Finally, you will need to close the file.

For example, write("Course: "); writeLn(courseName);

 

 As a light aside, here's a few excerpts from IT professionals and some of their experiences dealing with less-than-IT-literate users:-

About a month ago I received a support call from a user who claimed to be having trouble with her new scanner. Apparently a member of our support team had installed it while she was at lunch and it "just didn't scan anything." After asking her if it was powered along with the usual check-outs, I told her to start the scan program and click on scan in an attempt to scan in a test page. No luck. She said she could hear it working but the image it produced was black. I decided I would be better off seeing the situation for myself and told her "I'd be right up." She agreed and said she would continue to try and make it work herself while she waited. When I arrived at her office the problem was immediately apparent. Picture the scene yourself: a very frustrated young woman pressing a magazine cover firmly against the monitor in total confusion. I did my best to contain the evil pleasure I took while explaining to her the proper workings of her new flatbed scanner. –Jason K.

I had a user ask me for a floppy to back-up a file off of her hard drive. She then asked where to insert the floppy. I told her to insert it into the small slot that's about the same size as the disk itself. Unfortunately for me, I was unaware she had an external Zip drive. She decided to ram the floppy into the Zip drive as far as it would go. She then called me asking why she couldn't read anything off the floppy. -Mike P.

I was working tech support for a major corporate-level printer manufacturer and received a call from a user complaining that her printer was smearing toner all over the page. In fact, she told me, in the three months she had it, it's always done that. My first thought was that the envelope levers were flipped, so I had her open the left side of the printer to look. I asked her, "do you see the small gray levers under the big blue levers?" "No," she replied. "Are they behind this orange thing that says 'remove this?'" And of course her next question was, "should I remove it?" -Warren H.

I work for a holding company that supports several hundred employees. One day I get a call that a user's mouse is no longer working. I run through the normal battery of tests (Have you moved your computer, possibly unplugging the mouse, etc.). After having her check everything I could think of I thought I should personally examine the situation. As I approached her desk she says "see my little arrow won't move". I tried to hold back my laughter and instructed her to let go of her stapler and use the mouse instead. Another satisfied customer. -Jack A.