File size distribution: Difference between revisions

m
syntax highlighting fixup automation
m (J: use notation consistent with the earlier comment)
m (syntax highlighting fixup automation)
Line 16:
DOS 2.5 returns file size in number of sectors.
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
 
PROC SizeDistribution(CHAR ARRAY filter INT ARRAY limits,counts BYTE count)
Line 116:
SizeDistribution(filter,limits,counts,LIMITCOUNT)
PrintResult(filter,limits,counts,LIMITCOUNT)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/File_size_distribution.png Screenshot from Atari 8-bit computer]
Line 138:
=={{header|Ada}}==
{{libheader|Dir_Iterators}}
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Elementary_Functions;
with Ada.Directories; use Ada.Directories;
with Ada.Strings.Fixed; use Ada.Strings;
Line 196:
New_Line;
end loop;
end File_Size_Distribution;</langsyntaxhighlight>
{{out}}
<pre>Less than 10**0: 8
Line 210:
The platform independent way to get the file size in C involves opening every file and reading the size. The implementation below works for Windows and utilizes command scripts to get size information quickly even for a large number of files, recursively traversing a large number of directories. Both textual and graphical ( ASCII ) outputs are shown. The same can be done for Linux by a combination of the find, ls and stat commands and my plan was to make it work on both OS types, but I don't have access to a Linux system right now. This would also mean either abandoning scaling the graphical output in order to fit the console buffer or porting that as well, thus including windows.h selectively.
===Windows===
<syntaxhighlight lang="c">
<lang C>
#include<windows.h>
#include<string.h>
Line 284:
}
}
</syntaxhighlight>
</lang>
Invocation and textual output :
<pre>
Line 350:
{{libheader|POSIX}}
This works on macOS 10.15. It should be OK for Linux as well.
<langsyntaxhighlight lang="c">#include <ftw.h>
#include <locale.h>
#include <stdint.h>
Line 397:
printf("Total file size: %'lu\n", total_size);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 417:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <array>
#include <filesystem>
Line 468:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 491:
{{libheader| Winapi.Windows}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program File_size_distribution;
 
Line 598:
fileSizeDistribution('.');
readln;
end.</langsyntaxhighlight>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-03-02}}
<langsyntaxhighlight lang="factor">USING: accessors assocs formatting io io.directories.search
io.files.types io.pathnames kernel math math.functions
math.statistics namespaces sequences ;
Line 615:
current-directory get file-size-histogram dup
[ "Count of files < 10^%d bytes: %4d\n" printf ] assoc-each
nl values sum "Total files: %d\n" printf</langsyntaxhighlight>
{{out}}
<pre>
Line 634:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 705:
func main() {
fileSizeDistribution("./")
}</langsyntaxhighlight>
 
{{out}}
Line 733:
Uses a grouped frequency distribution. Program arguments are optional. Arguments include starting directory and initial frequency distribution group size. After the first frequency distribution is computed it further breaks it down for any group that exceeds 25% of the total file count, when possible.
</p>
<langsyntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase #-}
 
import Control.Concurrent (forkIO, setNumCapabilities)
Line 913:
mapM_ (displayFrequency fileCount) $ Map.assocs results
where
groupThreshold = round . (*0.25) . realToFrac</langsyntaxhighlight>
{{out}}
<pre style="height: 50rem;">$ filedist ~/Music
Line 1,000:
From there, we can bucket them by factors of ten, then display the limiting size of each bucket along with the number of files contained (we'll sort them, for legibility):
 
<langsyntaxhighlight Jlang="j"> ((10x^~.),.#/.~) <.10 ^.1>. /:~;{:|:dirtree '~'
1 2
10 8
Line 1,008:
100000 9
1000000 4
10000000 4</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using Humanize
 
function sizelist(path::AbstractString)
Line 1,039:
end
 
main(".")</langsyntaxhighlight>
 
{{out}}
Line 1,057:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import java.io.File
Line 1,104:
fun main(args: Array<String>) {
fileSizeDistribution("./") // current directory
}</langsyntaxhighlight>
 
{{out}}
Line 1,131:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">SetDirectory[NotebookDirectory[]];
Histogram[FileByteCount /@ Select[FileNames[__], DirectoryQ /* Not], {"Log", 15}, {"Log", "Count"}]</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import math, os, strformat
 
const
Line 1,181:
echo fmt"Size in {rangeString: 14} {count:>7} {100 * count / total:5.2f}%"
echo ""
echo "Total number of files: ", sum(counts)</langsyntaxhighlight>
 
{{out}}
Line 1,203:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use File::Find;
use List::Util qw(max);
 
Line 1,230:
 
sub fsize { $fsize{ log10( (lstat($_))[7] ) }++ }
sub log10 { my($s) = @_; $s ? int log($s)/log(10) : 0 }</langsyntaxhighlight>
{{out}}
<pre>File size distribution in bytes for directory: .
Line 1,244:
=={{header|Phix}}==
Works on Windows and Linux. Uses "proper" sizes, ie 1MB==1024KB. Can be quite slow at first, but is pretty fast on the second and subsequent runs, that is once the OS has cached its (low-level) directory reads.
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sizes</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
Line 1,280:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"files &lt; %s: %s%,d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ri</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,300:
The distribution is stored in a '''collections.Counter''' object (like a dictionary with automatic 0 value when a key is not found, useful when incrementing). Anything could be done with this object, here the number of files is printed for increasing sizes. No check is made during the directory walk: usually, safeguards would be needed or the program will fail on any unreadable file or directory (depending on rights, or too deep paths, for instance). Here links are skipped, so it should avoid cycles.
 
<langsyntaxhighlight lang="python">import sys, os
from collections import Counter
 
Line 1,331:
print("Total %d bytes for %d files" % (s, n))
 
main(sys.argv[1:])</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define (file-size-distribution (d (current-directory)) #:size-group-function (sgf values))
Line 1,362:
(module+ test
(call-with-values (λ () (file-size-distribution #:size-group-function log10-or-so))
(report-fsd log10-or-so)))</langsyntaxhighlight>
 
{{out}}
Line 1,380:
By default, process the current and all readable sub-directories, or, pass in a directory path at the command line.
 
<syntaxhighlight lang="raku" perl6line>sub MAIN($dir = '.') {
sub log10 (Int $s) { $s ?? $s.log(10).Int !! 0 }
my %fsize;
Line 1,405:
my ($end, $bar) = $scaled.polymod(8);
(@blocks[8] x $bar * 8) ~ (@blocks[$end] if $end) ~ "\n"
}</langsyntaxhighlight>
 
{{out}}
Line 1,438:
 
Also, some Windows versions of the &nbsp; '''dir''' &nbsp; command insert commas into numbers, so code was added to elide them.
<langsyntaxhighlight lang="rexx">/*REXX program displays a histogram of filesize distribution of a directory structure(s)*/
numeric digits 30 /*ensure enough decimal digits for a #.*/
parse arg ds . /*obtain optional argument from the CL.*/
Line 1,483:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do j#=length(_)-3 to 1 by -3; _=insert(',', _, j#); end; return _</langsyntaxhighlight>
This REXX program makes use of &nbsp; '''LINESIZE''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console) so as to maximize the width of the histogram.
 
Line 1,548:
{{libheader|walkdir}}
{{works with|Rust|2018}}
<langsyntaxhighlight lang="rust">
use std::error::Error;
use std::marker::PhantomData;
Line 1,725:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,745:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func traverse(Block callback, Dir dir) {
dir.open(\var dir_h) || return nil
 
Line 1,773:
}
 
say "Total: #{total_size} bytes in #{files_num} files"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,790:
=={{header|Tcl}}==
This is with the '''fileutil::traverse''' package from Tcllib to do the tree walking, a '''glob''' based alternative ignoring links but not hidden files is possible but would add a dozen of lines.
<langsyntaxhighlight lang="tcl">package require fileutil::traverse
namespace path {::tcl::mathfunc ::tcl::mathop}
 
Line 1,808:
foreach key [lsort -int [dict keys $hist]] {
puts "[? {$key == -1} 0 {1e$key}]\t[dict get $hist $key]"
}</langsyntaxhighlight>
{{out}}
<pre>0 1
Line 1,822:
{{works with|Bourne Shell}}
Use POSIX conformant code unless the environment variable GNU is set to anything not empty.
<langsyntaxhighlight lang="sh">#!/bin/sh
set -eu
 
Line 1,859:
printf "\nTotal: %.1f %s in %d files\n",
total / (10 ** l), u[int(l / 3)], NR
}'</langsyntaxhighlight>
{{out}}
<pre>$ time ~/fsd.sh
Line 1,903:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "io" for Directory, File, Stat
import "os" for Process
import "/math" for Math
Line 1,950:
Fmt.print("= Number of files : $,5d", numFiles)
Fmt.print(" Total size in bytes : $,d", totalSize)
Fmt.print(" Number of sub-directories : $,5d", numDirs)</langsyntaxhighlight>
 
{{out}}
Line 1,975:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">pipe:=Thread.Pipe();
// hoover all files in tree, don't return directories
fcn(pipe,dir){ File.globular(dir,"*",True,8,pipe); }
Line 1,993:
println("%15s : %s".fmt(szchrs[idx,*], "*"*(scale*cnt).round().toInt()));
idx-=1 + comma();
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits