I'm building a program for a class that pulls all bytes from a raw file in blocks of 512 bytes, searches the beginning bytes of each block for JPG signatures, and upon finding JPG signatures, writes out a JPG image. I have successfully pulled one JPG from the raw file, however the course indicates there are several more. After debugging in GDB, I've noticed that the variable "jpgname" never seems to have a value, and also, stepping through the program, I regularly step to the "fclose(inptr)" line, as if it were within the main while() loop. Am I using GDB incorrectly? Am I using sprintf() incorrectly? I would appreciate any feedback on this issue.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
typedef uint8_t BYTE;
int main(void)
{
BYTE jpg1[4] = {0xff, 0xd8, 0xff, 0xe0};
BYTE jpg2[4] = {0xff, 0xd8, 0xff, 0xe1};
int open = 0;
FILE* outp;
char* jpgname = malloc(sizeof(char) * 8);
int counter;
//TODO - MAKE sure this isn't a bunch of garbage data
//open card file
FILE* inptr = fopen("card.raw", "r");
if (inptr == NULL)
{
printf("Could not open file\n");
return 2;
}
BYTE buffer[512];
fread(buffer, 512, 1, inptr);
//repeat until end of card
while(fread(buffer, 512, 1, inptr) > 0)
{
counter = 0;
//start of new jpg?
if((buffer[0] == jpg1[0] && buffer[1] == jpg1[1] && buffer[2] == jpg1[2] && buffer[3] == jpg1[3]) || (buffer[0] == jpg2[0] && buffer[1] == jpg2[1] && buffer[2] == jpg2[2] && buffer[3] == jpg2[3]))
{
sprintf(jpgname, "%d.jpg", counter);
if (open == 1)
{
//close
fclose(outp);
//name new file
outp = fopen(jpgname, "w");
//write new
fwrite(buffer, sizeof(buffer), 1, outp);
counter++;
}
else if (open == 0)
{
//write new file
outp = fopen(jpgname, "w");
fwrite(buffer, sizeof(buffer), 1, outp);
open = 1;
counter++;
}
}
else
{
if(open == 1)
{
fwrite(buffer, sizeof(buffer), 1, outp);
}
}
}
fclose(outp);
fclose(inptr);
//close any remaining files
}