RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.Rewrite Function

Creates a new file and opens it.

Pascal
procedure Rewrite(var F: File); overload;
procedure Rewrite(var F: File; Recsize: Word); overload;
C++
Rewrite(File F);
Rewrite(File F, Word Recsize);

System

In Delphi code, Rewrite creates a new external file with the name assigned to F. 

F is a variable of any file type associated with an external file using AssignFile. RecSize is an optional expression, which can be specified only if F is an untyped file. If F is an untyped file, RecSize specifies the record size to be used in data transfers. If RecSize is omitted, a default record size of 128 bytes is assumed. 

If an external file with the same name already exists, it is deleted and a new empty file is created in its place. 

If F is already open, it is first closed and then re-created. The current file position is set to the beginning of the empty file. 

If F was assigned an empty name, such as AssignFile(F,''), then after the call to Rewrite, F refers to the standard output file. 

If F is a text file, F becomes write-only. 

After calling Rewrite, Eof(F) is always true.

Note: {$I+} handles runtime errors using exceptions. When using {$I-}, use IOResult to check for I/O errors.
 

Delphi Examples: 

 

{
This example reads an entire file into a buffer with one
command and then writes it into a saved file.
}
procedure TForm1.Button1Click(Sender: TObject);
var
  FromF, ToF: file;
  NumRead, NumWritten: Integer;
  Buf: array[1..2048] of Char;
begin
  if OpenDialog1.Execute then     { Display Open dialog box }
  begin
    AssignFile(FromF, OpenDialog1.FileName);
    Reset(FromF, 1);    { Record size = 1 }
    if SaveDialog1.Execute then      { Display Save dialog box}
    begin
      AssignFile(ToF, SaveDialog1.FileName);    { Open output file }
      Rewrite(ToF, 1);  { Record size = 1 }
      Canvas.TextOut(10, 10, 'Copying ' + IntToStr(FileSize(FromF))
        + ' bytes...');
      repeat
        System.BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
        BlockWrite(ToF, Buf, NumRead, NumWritten);
      until (NumRead = 0) or (NumWritten <> NumRead);
      CloseFile(FromF);
      CloseFile(ToF);
    end;
  end;
end;
{
Rewrite example
}

procedure TForm1.Button1Click(Sender: TObject);
var F: TextFile;
begin
  AssignFile(F, 'NEWFILE.$$$');
  Rewrite(F);  // default record size is 128 bytes
  Writeln(F, 'Just created file with this text in it...');
  CloseFile(F);
  MessageDlg('NEWFILE.$$$ has been created in the ' + GetCurrentDir + ' directory.',
    mtInformation, [mbOk], 0, mbOK);
end;

 

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!