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.";

In reply to Re: Re: head truncate by sauoq
in thread head truncate by zentara

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.