Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 2/Files

Deutsch · English · Français · Български · 中文(中国) · 日本語

2D - Files (author: Tao Yue, state: changed)

Reading from a file instead of the console (keyboard) can be done by:

pascal
read(File_variable, Argument_list);
write(File_variable, Argument_list);

Similarly with readln and writeln. The output is stored into the variables named in Argument_list. File_variable is declared as follows:

pascal
var
  ...
  Filein, Fileout : text;

The text data type indicates that the file is just plain text.

After declaring a variable for the file, and before reading from or writing to it, we need to associate the variable with the filename on the disk and open the file. This can be done in one of two ways. Typically:

text
reset(File_variable, 'filename.extension');
rewrite(File_variable, 'filename.extension');

reset opens a file for reading, and rewrite opens a file for 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 introduced the assign notation. First you assign a filename to a variable, then you call reset or rewrite using only the variable.

pascal
assign(File_variable, 'filename.extension');
reset(File_variable);

The method of representing the path differs depending on your operating system. Windows uses backslashes and drive letters due to its DOS heritage (e.g. c:\directory\name.pas), while FreeBSD, macOS and Linux use forward slashes due to their UNIX heritage.

After you're done with the file, you can close it with:

pascal
close (File_variable);

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:

pascal
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.

From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 2/Files", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 3, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.