#include #define BLKSIZ 512 char ibuf[BLKSIZ]; int blksiz = BLKSIZ; int dbgflg = 0; /* Debug; print entry and value */ int main(argc, argv) int argc; char *argv[]; { char *arg; char *ofnm, *ifnm; register FILE *out, *in; int ooffset, nblks; int iwblks, inblks, ieblksz; int olstblk, cblk, rdsz, wrsz; long isize, osize; if ((argc < 5) || (argc > 6)) { printf("\ninsert {-d} \n"); exit(1); } argv++; argc--; for (;;) { arg = *argv; if (*arg++ != '-') break; argv++; argc--; switch (*arg) { case 'd': dbgflg++; printf("\n"); break; default: printf("Bad flag: %c", *arg); exit(1); } } ofnm = *argv++; argc--; out = fopen(ofnm, "r+b"); if (out == NULL) { printf("Error opening output file: '%s'\n", ofnm); exit(1); } ifnm = *argv++; argc--; in = fopen(ifnm, "rb"); if (in == NULL) { printf("Error opening input file: '%s'\n", ifnm); exit(1); } ooffset = atoi(*argv++); if (ooffset < 0) { printf("Bad offset: %d\n", ooffset); exit(1); } argc--; nblks = atoi(*argv++); if (nblks < 0) { printf("Bad size: %d\n", nblks); exit(1); } if (--argc > 0) { printf("Unneeded extra arg '%s'", *argv); exit(1); } if (fseek(in, 0, SEEK_END) != 0) { printf("Xfer size seek failed\n"); exit(1); } isize = ftell(in); iwblks = (isize / BLKSIZ); ieblksz = (isize % BLKSIZ); inblks = iwblks; if (ieblksz == 0) ieblksz = BLKSIZ; else inblks++; if (nblks == 0) nblks = inblks; if (nblks > inblks) { printf("Block number/size too large\n"); exit(1); } olstblk = (ooffset + nblks - 1); printf("\nStart/End Block: %d %d\n", ooffset, olstblk); printf("Size: %ld %d %d\n", isize, iwblks, ieblksz); /* // Strictly speaking, seek not needed with "a" if (fseek(out, 0, SEEK_END) != 0) { printf("Space size seek failed\n"); exit(1); } osize = ftell(out); */ if (fseek(in, 0, SEEK_SET) != 0) { printf("Read seek failed\n"); exit(1); } if (fseek(out, (ooffset * BLKSIZ), SEEK_SET) != 0) { printf("Write seek failed\n"); exit(1); } for (cblk = ooffset; (cblk <= olstblk); cblk++) { if (cblk == olstblk) blksiz = ieblksz; if ((rdsz = fread(&ibuf[0], sizeof(char), blksiz, in)) != blksiz) { printf("Read failed: block %d read %d\n", cblk, rdsz); exit(1); } if ((wrsz = fwrite(&ibuf[0], sizeof(char), blksiz, out)) != blksiz) { printf("Write failed: block %d write %d\n", cblk, wrsz); exit(1); } } fclose(in); fclose(out); printf("%d blocks read\n", (cblk - ooffset)); }