in reply to Re: Re: head truncate
in thread head truncate
Yikes! In fact there are more bugs and more severe bugs in mine than you point out.
That the die was of course meant to have an if and not an unless clause, is only a minor problem. The seeks are cosmetics too - shame on me.
But the "late truncate" was a nasty thinko indeed. Unfortunately your fix of testing the read length against the block size won't work correctly either, since it fails when the last read gets exactly BLOCKSIZE bytes directly before the end of the file.
The cool thing about the real fix is I got rid of the if that was bothering me before. I had a gut feeling that a correct solution should not require extra tests for small files that get truncated to zero and indeed, it doesn't.
#!/usr/bin/perl -w use strict; #deletes first numbytes of a file use constant BLOCKSIZE => 128*1024; die "Usage: $0 numbytes file [file ...]\n" if @ARGV < 2; my $trunc_bytes = shift @ARGV; my $files_done = 0; for(@ARGV) { my $fh; unless(open $fh, "+<", $_) { warn "Couldn't open $_: $!\n"; next; } my $filesize = -s $fh; while($filesize > $trunc_bytes + tell $fh) { seek $fh, $trunc_bytes, 1; my $bytes_read = read($fh, my $buffer, BLOCKSIZE); seek $fh, -$bytes_read -$trunc_bytes, 1; print $fh $buffer; } truncate $fh, tell $fh; close $fh; $files_done++; } exit ($files_done == 0);
I left my old code in place for comparisons.
Update: added a couple brackets and changed open(..) or .. into unless(open ..) {..}.
Update 2: pulled my $fh out of the open.
Makeshifts last the longest.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: head truncate
by sauoq (Abbot) on Sep 13, 2002 at 20:03 UTC | |
by Aristotle (Chancellor) on Sep 13, 2002 at 21:18 UTC | |
by sauoq (Abbot) on Sep 14, 2002 at 00:35 UTC |