Here's what I've come up with thus far. I know that there are three files to be found in the input binary file. The three files are found with this little program and written to the output file with their corresponding offsets. The pattern(4-byte hex) is what identified the location of these files. The first offset(of first file) appears to be correct, yet the following two are off by increasing numbers. Depending on what I try the second offset will be off by 10, 11, or 22 whereas the third file's offset will off by 22, 32, 100+. Something is wrong with my calculation and accumulation but I can't spot it. Lastly, I know that tempBuffer isn't correct within sprintf... I am trying to find the filesize which is located 7 bytes from the file headers(as a result of the incorrect calculations I don't think I could find it except maybe for the first file) I'm trying to find a function for easy conversion from the pointer so that it can be output sprintf.. any recommendations?
Code:
// The first three lines make the functions within
// the declared libraries available to the program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void performFileIO(const char *infile)
{
FILE *FileIn, *FileOut;
char inBuffer[BUFSIZ];
char tempBuffer[4];
char outStringData[256];
char *filesize, *endptr;
int currentFile = 1, position = 0; //, tempInteger = 0;
// properly open the files for reading and appending
FileIn = fopen(infile, "rb");
if (FileIn == NULL) {
printf("The file could not be opened, please check your file and location before trying again.\n");
exit(1);
}
printf("Enter the name and path for the output file: ");
gets(inBuffer);
FileOut = fopen(inBuffer, "a");
// marks the header of a file found within the input file
unsigned char pattern[] = {0xFF, 0x57, 0x50, 0x43};
while (!feof(FileIn)) {
position++;
if (fgetc(FileIn) == pattern[0]) {
tempBuffer[0] = pattern[0];
fread(tempBuffer + 1, sizeof(pattern) - 1, 1, FileIn);
//fread(tempBuffer, sizeof(pattern), 1, FileIn);
if (memcmp(pattern, tempBuffer, sizeof(pattern)) == 0) {
printf("Match Found.\n");
fseek(FileIn, 7, SEEK_CUR);
fread(tempBuffer, sizeof(pattern), 1, FileIn);
sprintf(outStringData, "%-5i\tOffset: %-12i\tSize: %d\n", currentFile++, position - 1, tempBuffer);
fwrite(outStringData, sizeof(char), strlen(outStringData), FileOut);
continue;
}
fseek(FileIn, -3, SEEK_CUR);
}
}
// close the files and at the same time flush the buffers
fclose(FileIn);
fclose(FileOut);
}
// program entry point
int main(int argc, char *argv[])
{
char buffer[BUFSIZ];
printf("Please enter the name and path of the binary file: ");
gets(buffer);
performFileIO(buffer);
printf("\n Done!\n Press enter to exit\n");
getchar();
return 0;
}