Truncate a file : truncate « File « Perl






Truncate a file

    

#!/usr/bin/perl
use warnings;
use strict;

my $file = "data.txt";
my $truncate_to = 100;

open READ, "$file" or die "Cannot open: $! \n";
while (<READ>) {
    last if $. == $truncate_to;
}
my $size = tell READ;
print "$. lines read ($size bytes) \n";
exit if $. < $truncate_to;   # already shorter
close READ;

print "Truncating to $size bytes...";
open WRITE, "+< $file" or die "Cannot write: $! \n";
truncate WRITE, $size;
print "done \n";
close WRITE;

   
    
    
    
  








Related examples in the same category

1.To truncate the data in a file, you can use the truncate function: