bincut.c 1.41 KB

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

/*
 *
 */
int
main(int argc, char *argv[])
{
    FILE	*in, *out = stdout;
    int		i, j, offset, length, has_mem = 0, junk[10];
    unsigned char	c;

    while ((argc > 1) && (argv[1][0] == '-')) {
	switch(argv[1][1]) {

	  case 'm':
	    has_mem = 1;
	    break;

	  case 'o':
	    if ((out=fopen(argv[2],"w"))==NULL) {
		fprintf(stderr,"%s : can't open file [%s] for output.\n",
			argv[0],argv[2]);
		exit(-1);
	    }
	    argc--;
	    argv++;
	    break;
	    
	  default:
	    fprintf(stderr,"option [%s] not recognized.\n", argv[1]);
	    break;

	}
	argc--;
	argv++;
    }

    if (argc < 4 && !has_mem) {
	fprintf(stderr,"usage : %s [-o outfile] file offset length\n",
		argv[0]);
	exit(-1);
    }

    if ((in=fopen(argv[1],"r"))==NULL) {
	fprintf(stderr,"%s : can't open file [%s]\n",argv[0],argv[1]);
	exit(-1);
    }

    if (has_mem) {
	fread(&(junk[0]), sizeof(int), 8, in);
	fread(&offset, sizeof(int), 1, in);
	fread(&length, sizeof(int), 1, in);

	rewind(in);
	fseek(in, length, SEEK_SET);
	fread(&length, sizeof(int), 1, in);
	rewind(in);


    } else {
	sscanf(argv[2],"%i",&offset);
	sscanf(argv[3],"%i",&length);
    }

    fprintf(stderr,"%s : cutting out %d bytes from offset %d...\n",
	    "bincut", length, offset);

    fseek(in, offset, SEEK_SET);

    while (length > 0) {
	fread(&c, sizeof(unsigned char), 1, in);
	fwrite(&c, sizeof(unsigned char), 1, out);
	length--;
    }

}