czarniecki
czarniecki

Reputation: 63

Find the biggest file in a directory. Perl

The program lists all files in a directory, their size, type and owner. In case file is a directory, owner is the owner of the biggest file in that directory (that's the problem).

use warnings;
use strict;
use diagnostics;

use feature 'say';
use File::Find;

my $dir = shift || die "Provide a directory name";
my @file;
my @owner;
my @size;
my @type;   
my $i = 0;

while( glob("$dir/*") )
{
    $file[$i] = $_;
        find(sub { $size[$i] += -s if -f }, $_);
    if( -d $file[$i] )
    {
        $type[$i] = "d";
        $owner[$i] = getpwuid((stat($_))[4]);
    }
    elsif ( -l $file[$i] )
    {
        $type[$i] = "l";  
            $owner[$i] = getpwuid((stat($_))[4]);
    }
    else 
    {
        $type[$i] = "f";
            $owner[$i] = getpwuid((stat($_))[4]);
    }
    print "$file[$i]:$owner[$i]:$type[$i]:$size[$i]\n";
    $i++;

}

At this point in code

if( -d $file[$i] )
        {
            $type[$i] = "d";
            $owner[$i] = getpwuid((stat($_))[4]);
        }

i have to find the biggest file in this directory. I figured, that i should use find function, but not sure on how to do it.

Upvotes: 0

Views: 192

Answers (1)

Polar Bear
Polar Bear

Reputation: 6798

Please investigate the following code piece for compliance with your task.

The code uses recursion for directories, core component is glob function.

The result of directory lookup is returned as hash reference. Fill free to utilize this reference as your heart desire.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $dir = shift || die "Provide directory";

my $result = dir_lookup($dir);

say Dumper($result);

exit 0;

sub dir_lookup {
    my $dir = shift;

    my($record,$max);
    my @items = glob("$dir/*");

    $max = 0;

    for my $name ( @items ) {
        my $data;
        $data->{name}  = $name;
        $data->{size}  = -s $name;
        $data->{owner} = getpwuid((stat($name))[4]);
        $data->{type}  = 'link' if -l $name;
        $data->{type}  = 'file' if -f $name;
        $data->{type}  = 'dir'  if -d $name;
        if( $data->{size} > $max and -f $name ) {
            $max = $data->{size};
            $record->{file} = $data;
        }
        if( $data->{type} eq 'dir' ) {
            my $r = dir_lookup($data->{name});
            $data->{file}  = $r->{file};
            $data->{owner} = $r->{file}{owner};
        }
        push @{$record->{items}}, $data;
    }

    return $records;
}

Upvotes: 2

Related Questions