in reply to Re: head truncate
in thread head truncate
Untested, but no glaring mistakes obvious to me. If you see any, yell at me.
You need @ARGV > 1 because > 2 will fail for the minimum of two args.
Your WHENCE arguments to your seeks are all second instead of third where they belong.
As long as that inner while loop is entered, that last truncate() will always occur immediately after your read fails. Which means you will be at the end of the file and, since you truncate from tell() to the end, you won't truncate anything.
Update: Here is mine. It's based on yours but I've fixed the errors and simplified it a bit (as far as functionality goes.) I also introduce the $total_in variable to make the math a little clearer. Addendum: Aristotle found a bug in this code which surfaces when the last read is exactly BLOCKSIZE bytes long. See his reply and my reply to his reply for two different fixes.
#!/usr/bin/perl -w use strict; use constant BLOCKSIZE => 128 * 1024; die "Usage: $0 numbytes file" unless @ARGV > 1; my $remove_bytes = shift @ARGV; my $file = shift @ARGV; open(my $fh, "+<", $file) or die "Couldn't open $file: $!\n"; if(-s $fh > $remove_bytes ) { seek $fh, $remove_bytes, 0; my $total_in = 0; while(my $bytes_in = read $fh, my $buf, BLOCKSIZE) { seek $fh, $total_in, 0; print $fh $buf; last if $bytes_in < BLOCKSIZE; $total_in += $bytes_in; seek $fh, $remove_bytes + $total_in, 0; } } truncate $fh, tell $fh;
-sauoq "My two cents aren't worth a dime.";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: head truncate
by Aristotle (Chancellor) on Sep 13, 2002 at 13:26 UTC | |
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 |