Difference between revisions of "File"

From Free Pascal wiki
Jump to navigationJump to search
m (Fixed syntax highlighting; deleted category included in page template)
 
(16 intermediate revisions by 10 users not shown)
Line 1: Line 1:
In this article, for the sake of ease of understanding, [[Reserved words|reserved word]]s in Pascal are shown in UPPER CASE even though the Pascal lanugage is not case sensitive.
+
{{File(page)}}
  
When used in a [[Pascal]] program, a '''file''' is a variable which may be used to retrieve data from by reading the file [[Variable|variable]], or to send data to the file variable, or for both reading and writing. A file differs from normal variables in a program in that the information within the file is usually available even after the program [[terminate]]s.
+
In a [[Pascal]] program a variable of type '''file''' may be used to read, write or both read and write to a file. A file variable is (usually) associated with a file on a disk using the [[AssignFile]] procedure (older, equivalent name: just [[Assign]]).
 +
(See [[File Handling In Pascal]] for a more object oriented approach and more examples.)
  
The Pascal source format is
+
= File types =
:VAR filname : FILE;
 
  
Where '''filname''' is the file variable used to access the file.  The word ''file'' itself is a [[Reserved word|reserved word]] in Pascal.
+
== Untyped binary ==
  
When a file is defined in this fashion, it is called an ''[[untyped]]'' file; it may be used to store essentially anything.
+
The type '''file''' represents an ''untyped'' binary file. ''Untyped'' means it's just a sequence of data (bytes). It may be used to store essentially anything. It can be read by '''BlockRead''' and written to by '''BlockWrite''' procedures. The word ''file'' itself is a [[Reserved word|reserved word]] in Pascal. Example:
  
A typical type of file used for plain documents is a '''file [[Of|of]] [[Char|char]]''' and is defined by the compiler using the shorthand name [[Text|text]]. As such, the following two declarations should be equivalent:
+
<syntaxhighlight lang=pascal>
 +
{$mode objfpc}{$H+}
 +
var
 +
  MyFile: file;
 +
  Data: array [0..99] of Byte;
 +
begin
 +
  AssignFile(MyFile, 'a');
 +
  Reset(MyFile, 1 { size of read chunk });
 +
  try
 +
    BlockRead(MyFile, Data, SizeOf(Data));
 +
  finally
 +
    CloseFile(MyFile);
 +
  end;
 +
end.</syntaxhighlight>
  
:VAR filname : FILE OF char;
+
For larger example code, see [http://www.freepascal.org/docs-html/rtl/system/blockread.html BlockRead documentation].
:VAR filname : text;
 
  
In the above example, the [[Identifier|identifier]] used (''filname'') is the file [[Variable|variable]] which is used to do input, output, or both, to the actual file.  The file variable, however, is not the actual file; the file variable must be tied to the actual file  by a [[RTL|run-time library]] routine.  In most cases, this is done via the [[assign]] procedure followed by use of the [[reset]] or [[rewrite]] procedure.  In the case of specialized files such as databases, it is done via some other method than the standard ones, in order to allow a file variable to actually read from and/or write to the actual [[File|file]] itself using specialized routines.
+
== Typed binary ==
  
A file variable is used either for input, for output, or for both input and output (I/O).  A file may be a screen and/or keyboard, a modem, a light pen, a touch screen, a mouse, an area of storage on disk, a socket for connecting to the Internet, or it could be some other device depending on how the run-time library ties the file.  In some cases, actual memory can be defined as a file; this was used in the case of a ram disk.
+
The type [http://www.freepascal.org/docs-html/ref/refsu21.html '''file of <type>'''], where <type> is any simple type (no references/pointers) or record type, is a binary file representing a sequence of <type> values. For example, you can have files that are a sequence of integers, floating-point values, or records (as long as all record fields are also simple types).
  
Some of these devices are connected through various specialized [[library|libraries]] instead of treating them as actual files.  For example, databases are not normally accessed directly as a simple file which is read or written, they are usually accessed either through a set of database handling procedures and functions in an external unit or library, or are accessed via [[SQL]] commands sent to a procedure or function.  Programs that communicate with the Internet usually use a set of routines called [[Sockets|sockets]] under Unix-based operating systems, or using the [[Winsock]] routines on Microsoft Windows, which essentially provide the same functions as the Unix ''sockets'' routines.
+
<syntaxhighlight lang=pascal>
 +
{$mode objfpc}{$H+}
 +
var
 +
  MyFile: file of Single;
 +
  Data: Single;
  
Generally, the standard [[Pascal]] language does not distinguish between types of files, treating all files the same, allowing them to be accessed via the [[Read|read]], [[readln]], [[Write|write]] and [[writeln]] standard procedures.  Some Pascal Compilers also used the [[Get]] and [[Put]] routines for I/O.
+
begin
 +
  AssignFile(MyFile, 'singlevalues.bin');
 +
  try
 +
    Reset(MyFile);
 +
    Read(MyFile, Data);
  
Enhanced versions of Pascal such as [[UCSD Pascal]], [[Turbo Pascal]], and, of course, FPC Pascal have added features to indicate that a file is specifically a screen or a disk file, and to allow for such functions as naming of disk files, random access, appending to the end and deleting of files as needed.
+
  finally
 +
    CloseFile(MyFile);
 +
  end;
 +
end.</syntaxhighlight>
  
 +
== Text file ==
 +
 +
The type [[Text|TextFile]] (older, equivalent name: Text) represents a text file. Note that this is different than just '''file of char'''. There are various comfortable read and write operations available for text files, that parse integers, floating-point values and other types. Also, line endings are properly dealt with when you use text files.
 +
 +
See [[Text|TextFile]] page for more information and examples.
 +
 +
= Working with files =
 +
 +
Working with all file types is similar:
 +
# Associate a file with data. ''Usually'' by calling [[AssignFile]]. An older, equivalent name is [[Assign]]. (With the advent of GUI libraries there arose the possibility of name clashes with the names of some traditional Pascal file routines. TPersistent and TForm (a TPersistent descendent) have Assign and Close methods. Because of this, confusion can arise if you write Assign or Close in TForm methods, hence AssignFile and CloseFile were introduced as aliases for the traditional Assign and Close, to prevent inadvertently calling an unintended procedure. In non-GUI code you may of course use the original Assign and Close, and save a bit of typing).
 +
# Open the file by [[Reset]] (read existing file, and maybe write --- see below), [[Rewrite]] (clear contents and write), or [[Append]] (keep contents and write). In case of [[Reset]] on an untyped binary file, the global [[FileMode]] variable determines if you can only read (fmOpenRead), or both read and write (fmOpenReadWrite), to the file.
 +
# Then read/write file data by [[Read|read]], [[readln]], [[Write|write]] and [[writeln]] standard procedures.  Some Pascal Compilers also used the [[Get]] and [[Put]] routines for I/O. For untyped binary files, use [[BlockRead]] and [[BlockWrite]].
 +
# At the end, release the necessary file resources (and possibly flush the data to be written) by calling [[CloseFile]] (older, equivalent name: just [[Close]]).
 +
 +
A file variable is used either for input, for output, or for both input and output (I/O). A file may be a screen and/or keyboard, a modem, a light pen, a touch screen, a mouse, an area of storage on disk, a socket for connecting to the Internet, or it could be some other device depending on how the run-time library ties the file.  In some cases, actual memory can be defined as a file; this was used in the case of a ram disk. You can customize where the file data is by initializing [http://www.freepascal.org/docs-html/rtl/sysutils/filerec.html FileRec record] (for untyped binary files) or [http://www.freepascal.org/docs-html/rtl/sysutils/textrec.html TextRec record] (for text files), instead of calling standard [[AssignFile]] ([[Assign]]) routines.
 +
 +
=See also=
 +
 +
* [[File Handling In Pascal]]
  
[[category:Pascal]]
 
  
 
{{File}}
 
{{File}}

Latest revision as of 00:14, 15 February 2020

Deutsch (de) English (en) français (fr)

In a Pascal program a variable of type file may be used to read, write or both read and write to a file. A file variable is (usually) associated with a file on a disk using the AssignFile procedure (older, equivalent name: just Assign). (See File Handling In Pascal for a more object oriented approach and more examples.)

File types

Untyped binary

The type file represents an untyped binary file. Untyped means it's just a sequence of data (bytes). It may be used to store essentially anything. It can be read by BlockRead and written to by BlockWrite procedures. The word file itself is a reserved word in Pascal. Example:

{$mode objfpc}{$H+}
var
  MyFile: file;
  Data: array [0..99] of Byte;
begin
  AssignFile(MyFile, 'a');
  Reset(MyFile, 1 { size of read chunk });
  try
    BlockRead(MyFile, Data, SizeOf(Data)); 
  finally
    CloseFile(MyFile);
  end;
end.

For larger example code, see BlockRead documentation.

Typed binary

The type file of <type>, where <type> is any simple type (no references/pointers) or record type, is a binary file representing a sequence of <type> values. For example, you can have files that are a sequence of integers, floating-point values, or records (as long as all record fields are also simple types).

{$mode objfpc}{$H+}
var
  MyFile: file of Single;
  Data: Single;

begin
  AssignFile(MyFile, 'singlevalues.bin');
  try
    Reset(MyFile);
    Read(MyFile, Data);

  finally
    CloseFile(MyFile);
  end;
end.

Text file

The type TextFile (older, equivalent name: Text) represents a text file. Note that this is different than just file of char. There are various comfortable read and write operations available for text files, that parse integers, floating-point values and other types. Also, line endings are properly dealt with when you use text files.

See TextFile page for more information and examples.

Working with files

Working with all file types is similar:

  1. Associate a file with data. Usually by calling AssignFile. An older, equivalent name is Assign. (With the advent of GUI libraries there arose the possibility of name clashes with the names of some traditional Pascal file routines. TPersistent and TForm (a TPersistent descendent) have Assign and Close methods. Because of this, confusion can arise if you write Assign or Close in TForm methods, hence AssignFile and CloseFile were introduced as aliases for the traditional Assign and Close, to prevent inadvertently calling an unintended procedure. In non-GUI code you may of course use the original Assign and Close, and save a bit of typing).
  2. Open the file by Reset (read existing file, and maybe write --- see below), Rewrite (clear contents and write), or Append (keep contents and write). In case of Reset on an untyped binary file, the global FileMode variable determines if you can only read (fmOpenRead), or both read and write (fmOpenReadWrite), to the file.
  3. Then read/write file data by read, readln, write and writeln standard procedures. Some Pascal Compilers also used the Get and Put routines for I/O. For untyped binary files, use BlockRead and BlockWrite.
  4. At the end, release the necessary file resources (and possibly flush the data to be written) by calling CloseFile (older, equivalent name: just Close).

A file variable is used either for input, for output, or for both input and output (I/O). A file may be a screen and/or keyboard, a modem, a light pen, a touch screen, a mouse, an area of storage on disk, a socket for connecting to the Internet, or it could be some other device depending on how the run-time library ties the file. In some cases, actual memory can be defined as a file; this was used in the case of a ram disk. You can customize where the file data is by initializing FileRec record (for untyped binary files) or TextRec record (for text files), instead of calling standard AssignFile (Assign) routines.

See also


File-related types, procedures and functions:

File - Text - AssignFile - CloseFile - Reset - Rewrite - Get - Put - Read - Readln - Write - Writeln