[英]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.