#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void performFileIO(const char *infile)
{
FILE *FileIn, *FileOut;
char inBuffer[BUFSIZ];
char tempBuffer[4], *tempptr;
char outStringData[256];
int currentFile = 1, position = 0;
// marks the header of a file found within the input file
const unsigned char pattern[] = {0xFF, 0x57, 0x50, 0x43};
long int fileLength;
// properly open the binary file for reading
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, "w+b");
// position the file marker at the beginning of file
fseek(FileIn, 0, SEEK_SET);
while (!feof(FileIn))
{
position++;
if (fgetc(FileIn) == pattern[0]) {
tempBuffer[0] = pattern[0];
fread(tempBuffer + 1, sizeof(pattern) - 1, 1, FileIn);
if (memcmp(pattern, tempBuffer, sizeof(pattern)) == 0) {
printf("Match Found.\n");
fseek(FileIn, 21, SEEK_CUR); // find the file size
fread(tempBuffer, sizeof(pattern), 1, FileIn); // four byte size of file found
fileLength = (tempBuffer[0] + tempBuffer[1] + tempBuffer[2] + tempBuffer[3]);
// retract to the pattern header
fseek(FileIn, -25, SEEK_CUR);
printf("%d\n", fileLength); // test -> returns -55
//fread(tempptr, sizeof(char), total, FileIn);
//fread(tempptr, sizeof(char), sizeof((int)*tempBuffer), FileIn); // read up to the full length of file
//sprintf(outStringData, "%-5i\tOffset: %-12i\tSize: %02x%02x%02x%02x\n", currentFile++, position - 1,
//tempBuffer[0], tempBuffer[1], tempBuffer[2], tempBuffer[3]);
//fwrite(outStringData, sizeof(char), strlen(outStringData), FileOut);
//fwrite(tempptr, sizeof(*tempBuffer), strlen(tempptr), FileOut);
//fwrite(tempptr, sizeof(char), sizeof((int)*tempBuffer), FileOut);
//fwrite(tempptr, sizeof(char), fileLength, FileOut);
fwrite(tempptr, sizeof(char) * fileLength, 1, FileOut);
break; // just to test one run through a matched loop
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;
}