I'm on PSet4 right now, implementing recovery.c. It seems to work all right but the only problem I'm having is that when checking if the opened "card.raw" returns NULL, the condition returns true. However, the file seems to be open as the program generates 16 JPGs just as described in PSet. Not really sure what's the cause and how to fix this. Please take a look at my code:
#include<stdio.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdlib.h>
// struct to check file size
struct stat st;
int main(int argc, char* argv[])
{
FILE* card = fopen("card.raw", "r");
if (card == NULL);
{
printf("Could not open the file.\n");
}
unsigned char buffer[512];
int filecount = 0;
// check filesize in bytes
stat("card.raw", &st);
int fileLength = st.st_size;
int blocksNumber;
// set a number of blocks to search in
if (fileLength % 512 == 0)
blocksNumber = fileLength / 512;
else
blocksNumber = fileLength / 512 + 1;
int found = 0;
FILE* recovered;
char filename[8];
for (int i = 0; i <= blocksNumber; i++)
{
fread(&buffer, 512, 1, card);
// if that's a consecutive file found
if (((buffer[0] == 0xff && buffer[1] == 0xD8 && buffer[2] == 0xff && buffer[3] == 0xe0) || ((buffer[0] == 0xff && buffer[1] == 0xD8 && buffer[2] == 0xff && buffer[3] == 0xe1))) && found == 1)
{
fclose(recovered);
sprintf(filename, "%03d.jpg", filecount);
recovered = fopen(filename, "w");
filecount += 1;
}
// if that's the first file found
if (((buffer[0] == 0xff && buffer[1] == 0xD8 && buffer[2] == 0xff && buffer[3] == 0xe0) || ((buffer[0] == 0xff && buffer[1] == 0xD8 && buffer[2] == 0xff && buffer[3] == 0xe1))) && found == 0)
{
sprintf(filename, "%03d.jpg", filecount);
recovered = fopen(filename, "w");
found = 1;
filecount += 1;
}
if (found == 1)
fwrite(&buffer, 512, 1, recovered);
}
fclose(recovered);
}
Thanks a lot!