[英]How get filesize in cross-platform way on delphi xe2
我有這個rutine知道文件大小:
(基於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;
但是,這會發出此警告:
[DCC Warning] Funciones.pas(61): W1002 Symbol 'FindData' is specific to a platform
我想知道是否存在一種干凈的跨平台方式來做到這一點。 我檢查了TFile類而沒找到它......
在Delphi XE2中, TSearchRec.Size
成員已經是Int64
(不確定哪個版本已更改)並且使用Windows上TSearchRec.FindData
字段的完整64位值填充,因此無需計算手動大小,例如:
{$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;
你得到的警告,因為FindData
的成員TSearchRec
結構是特定於Windows平台,但你並不需要擔心,因為在你的代碼,當你從Windows不同平台上,你不是在訪問該成員。
// condition if you are on the Windows platform
{$IFDEF MSWINDOWS}
// here you can access the FindData member because you are
// on Windows
Result := Int64(sr.FindData.nFileSizeHigh) shl Int64(32) +
Int64(sr.FindData.nFileSizeLow);
{$ELSE}
// here you can't use FindData member and you would even
// get the compiler error because the FindData member is
// Windows specific and you are now on different platform
{$ENDIF}
因為您已經檢查過您是否在Windows上運行,所以可以安全地在本地刪除警告,以便僅保留編譯器報告的“真實”警告:
if FindFirst(fileName, faAnyFile, sr ) = 0 then
{$IFDEF MSWINDOWS}
{$WARN SYMBOL_PLATFORM OFF}
result := Int64(sr.FindData.nFileSizeHigh) shl Int64(32) + Int64(sr.FindData.nFileSizeLow)
{$WARN SYMBOL_PLATFORM ON}
{$ELSE}
TDirectory.GetLastWriteTime(path);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.