I am struggling along with recover.c of Pset4. I have pieced together - from the instructions and inspiration from other users - a program that I think should work. However, it does not create any jpgs - none at all, zero, nada, niente, nichts.
I would be immensely grateful for suggestions where I have gone wrong and maybe also some suggestions on how to improve on my code.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//open the infile to inptr
FILE* inptr = fopen("card.raw", "r");
if(inptr == NULL)
{
printf("Cannot open card.raw!");
return 2;
}
//open outfile, setting it NULL to avoid Magic Number
FILE* outptr = NULL;
//make an array of 512 bytes/chars
unsigned char buffer[512];
//a numbering tracker for outfile naming
int number_jpg = 0;
//storage for the filename: array with size eight to store "000.jpg\0"
char name[8];
//start the loop reading in 512 bytes at a time which will stop when fread hits the end of the file
while(fread(buffer,sizeof(BYTE)*512, 1, inptr) == 1)
{
//check if the first bytes indicate a jpeg file
if(buffer[0]==0xff && buffer[1]==0xd8 && buffer[2]==0xff && (buffer[3]==0xe1 || buffer[3]==0xe2 || buffer[3]==0xe3 || buffer[3]==0xe4 || buffer[3]==0xe5 || buffer[3]==0xe6 || buffer[3]==0xe7 || buffer[3]==0xe8 || buffer[3]==0xe9 || buffer[3]==0xea || buffer[3]==0xeb || buffer[3]==0xec || buffer[3]==0xed || buffer[3]==0xee || buffer[3]==0xef))
{
//close old file (if there was one)
if(outptr!=NULL)
{
fclose(outptr);
}
//sprint the title to variable name in format "000.jpg"
sprintf(name, "%03d.jpg", number_jpg);
number_jpg++;
//open a new jpg file with write flag
outptr = fopen(name, "w");
//check if file opened
if(outptr==NULL)
{
printf("Cannot create %03d.jpg!\n", number_jpg);
return 2;
}
//write the first block of the new jpeg file
fwrite(buffer, sizeof(BYTE)*512,1,outptr);
}
//write the rest of the buffer until the if condition triggers the loop above
else if(outptr!=NULL)
{
fwrite(buffer, sizeof(BYTE)*512,1,outptr);
}
}
//close remaining files
fclose(inptr);
if(outptr!=0)
{
fclose(outptr);
}
return 0;
}