#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int move_buffer(char buffer[], char len) {
int i=0;
for (i = 0; i < len-1; i++) {
buffer[i] = buffer[i+1];
}
}
int found_match(char buffer[], char len, char search_stream[]) {
int i=0, match_count=0;
for (i = 0; i < len; i++) {
if (buffer[i] == search_stream[i]) {
match_count++;
}
}
if (!(match_count==len)) {
return 0;
}
return 1;
}
int put_replace_stream(FILE *filehandle, char len, char put_stream[]) {
fseek(filehandle, 0, SEEK_CUR);
int ret = fwrite(put_stream, sizeof(char), len, filehandle);
fseek(filehandle, 0, SEEK_CUR);
if (ret==len) {
//printf("\nwrote %d chars\n", ret);
return 1;
} else {
//printf("\nwrote %d chars\n", ret);
return 0;
}
}
int modify_file(char *org_filename, char len_seach_stream, char search_stream[],
char len_put_stream, char put_stream[]) {
char *buffer;
buffer = malloc(len_seach_stream*sizeof(char));
char new_char, dummy;
int n_replaced = 0;
FILE *fptr;
fptr = fopen(org_filename, "r+b");
if(fptr == NULL) {
return 2;
}
while(!feof(fptr)) {
move_buffer(buffer, len_seach_stream);
fread(&new_char, sizeof(char), 1, fptr);
buffer[len_seach_stream-1] = new_char;
if (found_match(buffer, len_seach_stream, search_stream)) {
//printf("Found Match");
if (put_replace_stream(fptr, len_put_stream, put_stream)) {
n_replaced++;
}
}
}
fclose(fptr);
printf("Found and put %d occurrences.", n_replaced);
return 0;
}
int main(int argc, char *argv[])
{
if(argc < 4) {
printf("Searches for a series of bytes within a file and replaces the bytes after those with a specified series. Search and replace up to 10 bytes.\nUsage: [executable] filename \"search bytes\" \"replace-after bytes\"\n");
return 1;
}
char *org_filename = argv[1];
char search_stream[10];
char put_stream[10];
int len_seach_stream=0, len_put_stream=0;
len_seach_stream = sscanf(argv[2], "%x %x %x %x %x %x %x %x %x %x", search_stream, search_stream+1, search_stream+2, search_stream+3, search_stream+4, search_stream+5, search_stream+6, search_stream+7, search_stream+8, search_stream+9);
len_put_stream = sscanf(argv[3], "%x %x %x %x %x %x %x %x %x %x", put_stream, put_stream+1, put_stream+2, put_stream+3, put_stream+4, put_stream+5, put_stream+6, put_stream+7, put_stream+8, put_stream+9);
printf("Search Length: %d\n", len_seach_stream);
printf("Replace Length: %d\n", len_put_stream);
modify_file(org_filename, len_seach_stream, search_stream, len_put_stream, put_stream);
return 0;
}