RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.FileSize Function

Returns the number of records in a file.

Pascal
function FileSize(var F): Integer;
C++
int FileSize( F);

System

In Delphi code, call FileSize to determine the size of the file specified by the file variable F. The size is expressed as the number of records in a record file. Thus: 

If the file is declared as a file of byte, then the record size defaults to one byte, and FileSize returns the number of bytes in the file. 

The Reset procedure can set the record size (in bytes) when it opens the file. In this case, FileSize returns the number of records in the file.

Note: If the file is declared as an untyped file and you don't specify a record size when you call Reset, then FileSize assumes a record size of 128. That is, FileSize gives the number of bytes divided by 128.
To use FileSize, the file must be open. If the file is empty, FileSize(F) returns 0.  

Delphi Examples: 

 

{
FileSize, Seek, FilePos example
This example displays a open dialog when the user clicks a button. When the user selects the file, it reports the size of the file, seeks to halfway through the file, and reports the file position at that point.
Note:   This example assumes the compiler flag $IOCHECKS ON ($I+). That is, it expects errors to generate exceptions rather than checking IOResult to be sure that I/O routines succeed.
} 
procedure TForm1.Button1Click(Sender: TObject);
var
   f: file of Byte;
   size: Longint;
   S: string;
   y: Integer;
begin
  if OpenDialog1.Execute then
  begin
    AssignFile(f, OpenDialog1.FileName);
    Reset(f);
    try
      size := FileSize(f);
      S := 'File size in bytes: ' + IntToStr(size);
      y := 10;
      Canvas.TextOut(5, y, S);
      y := y + Canvas.TextHeight(S) + 5;
      S := 'Seeking halfway into file...';
      Canvas.TextOut(5, y, S);
      y := y + Canvas.TextHeight(S) + 5;
      Seek(f, size div 2);
      S := 'Position is now ' + IntToStr(FilePos(f));
      Canvas.TextOut(5, y, S);
    finally
      CloseFile(f);
    end;
  end;
end;
{
The following example opens a file of your choice and reads
the entire file into a dynamically allocated buffer. The
buffer and the size of the file are then passed to a routine
that processes the text, and finally the dynamically
allocated buffer is freed and the file is closed.
} 
procedure TForm1.Button1Click(Sender: TObject);
var
  F: file;
  Size: Integer;
  Buffer: PChar;
begin
  if OpenDialog1.Execute then
  begin
    AssignFile(F, OpenDialog1.FileName);
    Reset(F, 1);
    try
      Size := FileSize(F);
      GetMem(Buffer, Size);
      try
        BlockRead(F, Buffer^, Size);
        Memo1.Lines.Add(Buffer);
      finally
        FreeMem(Buffer);
      end;
    finally
      CloseFile(F);
    end;
  end;
end;

 

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