Name

Rewrite Procedure

Syntax

procedure Rewrite(var F: TextFile);
procedure Rewrite(var F: File);
procedure Rewrite(var F: File; RecordSize: Integer);

Description

The Rewrite procedure opens a new file for writing. If the file already exists, its contents are discarded before opening the file. A TextFile is opened for write access only. A binary file is opened for read and write access. Rewrite is not a real procedure.

If the file is a typed binary file (e.g., file of something), use the second form of Reset, that is, pass the file variable only. If the file is an untyped binary file (just file), you can optionally supply the second argument to tell Delphi the record size. If you omit the record size, Delphi uses 128 bytes.

Errors

  • Rewrite reports I/O error 102 if you fail to call AssignFile prior to calling Rewrite.

  • If Rewrite cannot open the file, it reports the Windows error code as an I/O error.

Tips and Tricks

  • If the file is already open, it is closed first.

  • When using an untyped file, it is usually simplest to supply a record size of 1 when calling Rewrite, and then call BlockRead and BlockWrite to read and write as much data as you want. Alternatively, create a type for File of Byte, so you don’t need to set the record size in Rewrite.

Example

See Reset for an example.

See Also

Append Procedure, AssignFile Procedure, CloseFile Procedure, IOResult Function, Reset Procedure

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.