Search code examples
delphicross-platformcompiler-warningsfilesize

How get filesize in cross-platform way on delphi xe2


I have this rutine to know the filesize:

(Based on http://delphi.about.com/od/delphitips2008/qt/filesize.htm)

function FileSize(fileName : String) : Int64;
var
  sr : TSearchRec;
begin
  if FindFirst(fileName, faAnyFile, sr ) = 0 then
  {$IFDEF MSWINDOWS}
     result := Int64(sr.FindData.nFileSizeHigh) shl Int64(32) + Int64(sr.FindData.nFileSizeLow)
  {$ELSE}
     result := sr.Size
  {$ENDIF}
  else
     result := -1;

  FindClose(sr) ;
end;

However, this give this warning:

[DCC Warning] Funciones.pas(61): W1002 Symbol 'FindData' is specific to a platform

I wonder if exist a clean cross-platform way to do this. I check TFile class and not found it...


Solution

  • In Delphi XE2, the TSearchRec.Size member is already an Int64 (not sure which version that changed in) and is filled in with the full 64-bit value from the TSearchRec.FindData fields on Windows, so there is no need to calculate the size manually, eg:

    {$IFDEF VER230}
      {$DEFINE USE_TSEARCHREC_SIZE}
    {$ELSE}
      {$IFNDEF MSWINDOWS} 
        {$DEFINE USE_TSEARCHREC_SIZE}
      {$ENDIF} 
    {$ENDIF}
    
    function FileSize(fileName : String) : Int64; 
    var 
      sr : TSearchRec; 
    begin 
      if FindFirst(fileName, faAnyFile, sr ) = 0 then 
      begin
        {$IFDEF USE_TSEARCHREC_SIZE}
        Result := sr.Size;
        {$ELSE}
        Result := (Int64(sr.FindData.nFileSizeHigh) shl 32) + sr.FindData.nFileSizeLow;
        {$ENDIF} 
        FindClose(sr); 
      end
      else 
         Result := -1; 
    end;