The code compiled successfully, but only made two files 000.jpeg and 001.jpeg. I also cannot open these two files. I used valgrind to check if any memory issues. It's all good. Can I read one byte at a time when looking for jpeg signature and write a block of 512 when writing to new file? I don't know why there are only two output files? when I tried to open 001.jpeg. it shows "Unknown error: File size is bigger than allowed (8MB). Size is 16342528 bytes". why does the code keep writing into one file?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BLOCK_SIZE 512
typedef uint8_t BYTE;
int main (void)
{
//open the file to be recovered
FILE* in_file = fopen("card.raw", "r");
//check if file can be open
if (in_file == NULL)
{
printf("cannot open the file\n");
return 1;
}
//one block
BYTE buffer[BLOCK_SIZE];
//open a new file
FILE* image = NULL;
//keep track of how many images have been recovered
int counter = 0;
//read all blocks until end of file
while(fread(&buffer, sizeof(BYTE) * BLOCK_SIZE, 1, in_file) == 1)
{
//iterate through each block
for (int i = 0; i < BLOCK_SIZE; i++)
{
fread(&buffer[i], sizeof(BYTE), 1, in_file);
}
//if find a jpeg image
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
(buffer[3] == 0xe0 || buffer[3] == 0xe1))
{
//make sure start writing in a new file
if (image != NULL)
{
fclose(image);
}
char title[3];
//write a new file
sprintf(title, "%03d.jpg", counter);
counter++;
image = fopen(title, "a");
//make sure open a file successfully
if (image == NULL)
{
printf("Could not write the file.\n");
return 2;
}
//write a block
fwrite(&buffer, sizeof(BYTE) * BLOCK_SIZE, 1, image);
}
//write in existing file
else if (image != NULL)
{
fwrite(&buffer, sizeof(BYTE) * BLOCK_SIZE, 1, image);
}
}
//close input file
fclose(in_file);
return 0;
}