[ILUG] Truncating a binary file from the command-line

Colm Buckley colm at tuatha.org
Thu Jun 2 13:12:48 IST 2005


On 2 Jun 2005, at 12:49, Kieran.Tully AT acm.org wrote:

> Is there a simple way to truncate a file to a given length from the  
> command-line?

dd can copy a specified portion of the file (use bs= and count=) to  
another file.  If you want to truncate it "in place", the easiest way  
would be to write a small C program:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {

         /* note : no error-checking done; this is a demo only */

         if (truncate(argv[1], atoi(argv[2])) == 0) {
                 exit(0);
         } else {
                 perror("truncate failed");
                 exit(1);
         }
}

(compile using gcc -O2 -s -o truncate truncate.c, run with eg:  
"truncate file.name 5100")

If you can count on Perl being available:

perl -e 'truncate "filename", 5100;'

should work also.

     Colm

-- 
Colm Buckley / colm at tuatha.org / +353 87 2469146





More information about the ILUG mailing list