-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflipabit.c
49 lines (38 loc) · 1.1 KB
/
flipabit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if (argc != 4)
{
fprintf(stderr, "flipabit file newfile pos\n");
return 1;
}
char * infile = argv[1];
char * outfile = argv[2];
int editpos = atoi(argv[3]);
fprintf(stderr, "Editing \"%s\" into \"%s\" editing byte %d\n", infile, outfile, editpos);
FILE * in = fopen(infile, "rb");
FILE * out = fopen(outfile, "wb");
if (!in) { fprintf(stderr, "Couldnt open %s for reading\n", infile); return 1; }
if (!out) { fprintf(stderr, "Couldnt open %s for writing\n", outfile); return 1; }
int buffersize = 1024;
char buffer[buffersize];
int bytes = 0;
int totalbytes = 0;
int bitsflipped = 0;
while ((bytes = fread(buffer, 1, 1, in)) != 0)
{
if (totalbytes == editpos)
{
fprintf(stderr, "-- flipping a bit in byte %d\n", totalbytes);
buffer[0] = buffer[0] ^ 0x01;
bitsflipped++;
}
fwrite(buffer, 1, bytes, out);
totalbytes += bytes;
}
fclose(in);
fclose(out);
fprintf(stderr, "copied %d bytes and edited %d bits\n", totalbytes, bitsflipped);
return 0;
}