#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
/* Open memory card
Repeat until end of card:
Read 512 bytes of data into buffer
If Start of jpeg
If first jpeg (the jpeg header files in the first 512 bytes)
Else if not the first jpeg, then jpeg++, keep adding jpegs
Else (if continued: the 512 bytes of data doesn't have the header files)
Continue adding to the same jpeg
Close any remaining files*/
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
// A file in which we open the "card.raw" for reading
FILE *card = fopen(argv[1], "r");
if (card == NULL)
{
fprintf(stderr ,"File not present\n");
return 0;
}
uint8_t buffer[512]; // Allocate memory for jpeg in multiples of 512 bytes
int njpegs = 0; // = number of jpegs
bool found_jpeg = false;
char filename[8]; /*BYTE array[(malloc(8))] */
// Declare a file img (into which we want our images in)
FILE *img = NULL;
while (fread(buffer, 512, 1, card))
{
// If the image is a new one
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3] & 0xf0) == 0xe0))
{
if (found_jpeg == false)
{
found_jpeg = true;
}
else
{
fclose(img);
}
// sprintf the the jpeg to an array called filename
sprintf(filename, "%3i.jpg", njpegs);
// open the file "filename" for writing
img = fopen(filename, "a");
if (img == NULL)
{
return 1;
}
fwrite(buffer, 512, 1, img);
njpegs++;
}
else if (found_jpeg == true)
{
fwrite(buffer, 512, 1, img);
}
}
fclose(img);
fclose(card);
}
There is a segmentation fault every time I run the code. I ran the debugger and the problem seems to be in the while loop. The program runs, gets to the while, and then skips everything within the while loop and sort of jumps to fclose img
and terminates (segmentation fault).
I tried experimenting with a few different function to sort of loop through all the jpegs in the memory card, but none of them worked. I can't quite figure out something wrong here.
Please help!