delphi – 获取文件大小>然后获取总大小?
这应该很容易,但我似乎无法正确,因为我似乎混淆了自己并转换为字符串,整数和浮点数等等.
基本上,我在一列中填充带有FileNames的TListView,并在另一列中将File Size返回到相应的FileName.我使用从here找到的相当简洁的功能,看起来像这样: function FileSizeStr ( filename: string ): string; const // K = Int64(1000); // Comment out this line OR K = Int64(1024); // Comment out this line M = K * K; G = K * M; T = K * G; var size: Int64; handle: integer; begin handle := FileOpen(filename,fmOpenRead); if handle = -1 then result := 'Unable to open file ' + filename else try size := FileSeek ( handle,Int64(0),2 ); if size < K then result := Format ( '%d bytes',[size] ) else if size < M then result := Format ( '%f KB',[size / K] ) else if size < G then result := Format ( '%f MB',[size / M] ) else if size < T then result := Format ( '%f GB',[size / G] ) else result := Format ( '%f TB',[size / T] ); finally FileClose ( handle ); end; end; 返回值,例如:235.40 KB 所以有了上面的内容,我的TListView可能会像这样填充: 现在在Label Data Size中,我想返回Listview中文件的总大小,所以在这个例子中,Size列中的值需要加起来返回Total Size,如: 1.28 MB 313.90 KB 541.62 KB 270.96 KB 显然它不能像这样添加,因为值包含小数点,一些值可能在Kb中,而其他值在Mb中等.这是我的问题,我想不出一个简单的解决方案来添加(获取)总大小的文件,然后以相同的格式化字符串返回它,如图所示. 我真的很感激如何使用这种数据的一些见解或提示,我只是无休止地混淆自己与不同的转换等,并不确定哪种方式来做到这一点. 提前谢谢了 :) 更新1 根据Marc B的建议,我将功能改为以下似乎有效: var iFileSize: Int64; implementation function GetSizeOfFile(FileName: string): Int64; var Handle: Integer; begin Handle := FileOpen(FileName,fmOpenRead); if Handle = -1 then MessageDlg('Unable to open file ' + FileName,mtError,[mbOk],0) else try iFileSize := iFileSize + FileSeek(Handle,2); finally FileClose(Handle); end; Result := iFileSize; end; function FormatFileSize(AValue: Int64): string; const K = Int64(1024); M = K * K; G = K * M; T = K * G; begin if AValue < K then Result := Format ( '%d bytes',[AValue] ) else if AValue < M then Result := Format ( '%f KB',[AValue / K] ) else if AValue < G then Result := Format ( '%f MB',[AValue / M] ) else if AValue < T then Result := Format ( '%f GB',[AValue / G] ) else Result := Format ( '%f TB',[AValue / T] ); end; 如果他们需要它可能对其他人有用:) 更新2 另外,请参阅Ken White发布的答案,该答案提供了更多有价值的信息,以及GetSizeOfFile功能的更新更新,效果很好: 解决方法
将“获取文件信息”从“格式化大小字符串”分成两个单独的函数.文件信息函数获取文件大小并将其添加到运行总计中,然后调用格式化函数将简单整数转换为“nice”字符串.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |