/* * applybp - Apply binary patch * Brian Katzung 15 August 1993 * * Copyright 1993 by Brian Katzung. All rights reserved. * Permission is granted to use or modify this code as long as this * notice is preserved and modified versions are clearly marked. * This software may not be sold without written permission from the * author. * * This software is provided strictly on an "as-is" basis. * Use it at your own risk. * * usage: applybp old patch new */ #include int GetOldChar (OldFile) FILE *OldFile; { int OldChar; while ((OldChar = getc(OldFile)) == 0) ; if (OldChar == EOF) { rewind(OldFile); while ((OldChar = getc(OldFile)) == 0) ; if (OldChar == EOF) { fputs("Old file must have non-zero contents\n", stderr); exit(1); } } return OldChar; } int main (ac, av) char **av; { int PatchChar; int OldChar; int XORChar; int i; int j; FILE *OldFile; FILE *NewFile; FILE *PatchFile; if (ac != 4) { fputs("usage: applybp old patch new\n", stderr); exit(1); } if ((OldFile = fopen(av[1], "r")) == NULL) { perror(av[1]); return 1; } if ((PatchFile = fopen(av[2], "r")) == NULL) { perror(av[2]); return 1; } if (access(av[3], 0) == 0) { fprintf(stderr, "A file called %s already exists\n", av[3]); return 1; } if ((NewFile = fopen(av[3], "w")) == NULL) { perror(av[3]); return 1; } while ((i = getc(PatchFile)) != EOF) { /* * Non-zero characters */ if (i != 0) { if (i > 1) { if ((XORChar = getc(PatchFile)) == EOF) { fputs( "Premature EOF encountered in patch file\n", stderr); return 1; } } for (j = i & 255; --j >= 0; ) { if ((PatchChar = getc(PatchFile)) == EOF) { fputs( "Premature EOF encountered in patch file\n", stderr); return 1; } PatchChar ^= GetOldChar(OldFile); putc(PatchChar, NewFile); XORChar ^= PatchChar; } if (i > 1 && XORChar != 0) { fputs( "Patch file does not correspond to old file\n", stderr); return 1; } } /* * Zero characters */ if ((i = getc(PatchFile)) != EOF && i != 0) { for (i &= 255; --i >= 0; putc(0, NewFile)) ; } } return 0; }