Add to Gambit REPL some functions to send SMS and take pictures (this functionnality...
[gambit-c.git] / prebuilt / windows / binpatch.c
blobecac170d7402b54069b83f71d364ac9873a6b698
1 /* File: "binpatch.c", Time-stamp: <2007-04-23 22:00:14 feeley> */
3 /* Copyright (c) 2007 by Marc Feeley, All Rights Reserved. */
5 /* This is a tool for patching binary files */
7 /*---------------------------------------------------------------------------*/
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
13 void binpatch (char *oldstr, char *newstr, char *filename)
15 int oldlen = strlen (oldstr) + 1;
16 int newlen = strlen (newstr) + 1;
17 int step = 65536;
18 int buflen = step + oldlen - 1;
19 int pos;
20 int len;
21 char *buf;
22 FILE *f;
24 buf = malloc (buflen);
25 if (buf == NULL)
27 printf ("Could not allocate buffer\n");
28 exit (1);
31 f = fopen (filename, "r+b");
33 if (f == NULL)
35 printf ("Could not open file \"%s\"\n", filename);
36 exit (1);
39 fseek (f, 0, SEEK_END);
40 len = ftell (f);
41 if (len < 0)
43 fclose (f);
44 printf ("Could not seek\n");
45 exit (1);
48 pos = 0;
50 while (pos < len)
52 int i;
53 int n = len-pos;
54 if (n > buflen)
55 n = buflen;
56 int x = fseek (f, pos, SEEK_SET);
57 if (x < 0)
59 fclose (f);
60 printf ("Could not seek\n");
61 exit (1);
63 if (fread (buf, 1, n, f) != n)
65 fclose (f);
66 printf ("Could not read\n");
67 exit (1);
69 n = n - oldlen + 1;
70 for (i=0; i<n; i++)
71 if (buf[i] == oldstr[0])
73 int j;
74 for (j=1; j<oldlen; j++)
75 if (buf[i+j] != oldstr[j])
76 goto fail;
77 pos = pos + i;
78 x = fseek (f, pos, SEEK_SET);
79 if (x < 0)
81 fclose (f);
82 printf ("Could not seek\n");
83 exit (1);
85 if (fwrite (newstr, 1, newlen, f) != newlen)
87 fclose (f);
88 printf ("Could not write\n");
89 exit (1);
91 fclose (f);
92 return;
93 fail: ;
95 pos += step;
98 fclose (f);
99 printf ("Did not find string in file \"%s\"\n", filename);
100 exit (1);
103 int main (int argc, char *argv[])
105 int i;
107 if (argc < 3)
109 printf ("Usage: binpatch <old-string> <new-string> <filename>...\n");
110 exit (1);
113 for (i=3; i<argc; i++)
114 binpatch (argv[1], argv[2], argv[i]);
116 return 0;
119 /*---------------------------------------------------------------------------*/