Learn Pascal
2D - Files

Using files for input/output is a bit of a sticking point. Different Pascal compilers do it in different ways. However, the method of reading/writing to the file is the same across all compilers:
     read (file_variable, argument_list);
     write (file_variable, argument_list);

Same thing with readln and writeln.

In addition, most Pascal systems require that you declare a file variable in the variable section:
     var
        ...
        filein, fileout : text;

The text data type is usually used. There are other file types, but that's left for a later lesson.

The differences between Pascal compilers arises when you open a file for reading or writing. In most Pascal compilers, including Metrowerks Codewarrior and the Pascal translator included with Unix/Linux, use:
     reset (file_variable, 'filename.extension');
to open a file for reading. Use:
     rewrite (file_variable, 'filename.extension');
to open a file for writing. Note that you can't open a file for both reading and writing. A file opened with reset can only be used with read and readln. A file opened with rewrite can only be used with write and writeln.

Turbo Pascal does it differently. First you assign a filename to a variable, then you call reset or rewrite using only the variable.

     assign (file_variable, 'filename.extension');
     reset (file_variable)
The method of representing the path differs depending on your operating system. Examples:
   Unix:    ~login_name/filename.ext
   DOS/Win: c:\directory\name.pas
   Mac:     Disk_Name:Programs Directory:File Name.pas

You should close your file before your program ends! This is the same for all compilers:
     close (File_Identifier);

Here's an example of a program that uses files. This program was written for Turbo Pascal and DOS, and will create file2.txt with the first character from file1.txt:

   program CopyOneByteFile;

   var
      mychar : char;
      filein, fileout : text;

   begin
      assign (filein, 'c:\file1.txt');
      reset (filein);
      assign (fileout, 'c:\file2.txt');
      rewrite (fileout);
      read (filein, mychar);
      write (fileout, mychar);
      close(filein);
      close(fileout)
   end.


Previous lesson

Next lesson

Contents

Index

e-mail me


taoyue@mit.edu
Copyright © 1997-2001 Tao Yue. All rights reserved.