Mega Code Archive

 
Categories / Delphi / Examples
 

Getting a filesize

GetFileSize provides no way to turn a filesize into a descriptive string, this algorithm does function GetAFileSize(SizeInBytes: Integer): String; const Preffixes: array[0..3] of String = //Common file sizes preffixes (' Bytes', ' KB', 'MB', ' GB'); //Change if you want to anything that suits FormatSpecifier: array[Boolean] of String = ('%n', '%.2n'); //the way we format the string; var i: integer; //A counter TmpSize: Real; //A temporary variable begin i := -1; //Avoid compiler complain tmpSize := SizeInBytes; //Avoid compiler complain while (i <= 3) do //Main cycle it is done while i < High(Preffixes) but since // a file will rarely pass a GB up to 3 begin TmpSize := TmpSize / 1024; //1 MB = 1024 KB, 1 KB = 1024 Bytes, 1 Byte = 8 Bits, 1 bit = nothing inc( i ); //increment counter and select preffix string if Trunc( TmpSize )= 0 then //we reached a maximum nuber of divisions so begin TmpSize := TmpSize * 1024; //Tmpsize was divided 1 time more than necessary Break; //Exit of loop; end; end; //Actual formatting routine Result := Format(FormatSpecifier[((Frac(TmpSize)*10) >1)], [TmpSize]) + Preffixes[i]; end; Notes of interest: * These algorithm relies on delphi native format function, wich kind of limits it * It isnot part of windows api, you have to copy and paste it whenever you use it * Unlike windows api it has correct rounding and can be extended