File size distribution: Difference between revisions

Content added Content deleted
m (Bug fix)
Line 806: Line 806:
Number of inaccessible files : 0
Number of inaccessible files : 0
</pre>
</pre>

=={{header|Nim}}==
<lang Nim>import math, os, strformat

const
MaxPower = 10
Powers = [1, 10, 100]

func powerWithUnit(idx: int): string =
## Return a string representing value 10^idx with a unit.
if idx < 0:
"0B"
elif idx < 3:
fmt"{Powers[idx]}B"
elif idx < 6:
fmt"{Powers[idx - 3]}kB"
elif idx < 9:
fmt"{Powers[idx - 6]}MB"
else:
fmt"{Powers[idx - 9]}GB"


# Retrieve the directory path.
var dirpath: string
if paramCount() == 0:
dirpath = getCurrentDir()
else:
dirpath = paramStr(1)
if not dirExists(dirpath):
raise newException(ValueError, "wrong directory path: " & dirpath)

# Distribute sizes.
var counts: array[-1..MaxPower, Natural]
for path in dirpath.walkDirRec():
if not path.fileExists():
continue # Not a regular file.
let size = getFileSize(path)
let index = if size == 0: -1 else: log10(size.float).toInt
inc counts[index]

# Display distribution.
let total = sum(counts)
echo "File size distribution for directory: ", dirpath
echo ""
for idx, count in counts:
let rangeString = fmt"[{powerWithUnit(idx)}..{powerWithUnit(idx + 1)}[:"
echo fmt"Size in {rangeString: 14} {count:>7} {100 * count / total:5.2f}%"
echo ""
echo "Total number of files: ", sum(counts)</lang>

{{out}}
<pre>File size distribution for directory: /home/xxx

Size in [0B..1B[: 2782 1.28%
Size in [1B..10B[: 145 0.07%
Size in [10B..100B[: 2828 1.30%
Size in [100B..1kB[: 20781 9.55%
Size in [1kB..10kB[: 85469 39.29%
Size in [10kB..100kB[: 86594 39.81%
Size in [100kB..1MB[: 16629 7.64%
Size in [1MB..10MB[: 2053 0.94%
Size in [10MB..100MB[: 221 0.10%
Size in [100MB..1GB[: 38 0.02%
Size in [1GB..10GB[: 0 0.00%
Size in [10GB..100GB[: 0 0.00%

Total number of files: 217540</pre>


=={{header|Perl}}==
=={{header|Perl}}==