'Ve been working on recover for days. It finally compiled but not sure what's happening coz it ain't creating any intended file (from "%03d.jpg") and I can't open the file (it gets automatically deleted after popping error message "could not open file"). Below is an image of the funny file the program created:
and here is my code so far
#include <stdio.h>
include
include
typedef uint8_t BYTE;
typedef struct { BYTE block; } JPEG;
int main(void)
{
// declare variables
int file_num = 0;
char title[8];
uint8_t data[512];
JPEG img;
// open card file
FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
printf("Could not open %s.\n", "card.raw");
return 1;
}
// open new file
FILE* new_file = fopen(title, "a");
// measure card.raw size
long long card = sizeof("card.raw");
// put stream at the beginning of file
fseek(file, 0, SEEK_SET);
// to repeat until end of card
for(int i = 0, n = card / 512; i <= n; i++)
{
// read 512 bytes into a buffer
fread(&data, 512, 1, file);
// start of a new jpg?
// check for jpg signature
if(data[0] == 0xff &&
data[1] == 0xd8 &&
data[2] == 0xff &&
(data[3] >= 0xe0 && data[3] <= 0xef))
{
// yes, then write 512 bytes to new file
sprintf(title, "%03d.jpg", file_num);
file_num++;
// write file data
fwrite(&img, 512, 1, new_file);
}
else
{
// already found a jpg?
// yes, then ...(keep track and write into JPEG)
if(file_num > 0)
{
// continue writing jpg data
fwrite(&img, 512, 1, new_file);
}
// no, then don't write at all or skip
else
{
// move stream to the next block
fseek(file, (i + 1) * 512, SEEK_CUR);
}
}
i++;
// eof??
if(fread(&data, card, 1, file) == 0)
{
printf("%i\n files have been recovered!!", file_num);
}
}
// close any remaining files
// close source file
fclose(file);
// close output file
fclose(new_file);
// that's all folks
return 0;
}
Could anyone please help give me a hint where this program goes wrong? Thanking you beforehand.