for recover my code returns 51 jpegs, was wondering where i went wrong? none of the jpegs seem viewable from vscode as well.
int main (int argc, char *argv[])
{
if (argc < 2|| argc <= 1)
{
printf("Usage: ./recover filename\n");
return 1;
}
char *name = argv[1];
FILE *input = fopen(name, "r");
if (input == NULL)
{
printf("File input null\n");
return 1;
}
fseek(input, 0 , SEEK_END);
long totalbyte = ftell(input); //size = total no. of byte
fseek(input, 0, SEEK_SET);
// calc no. of blocks
// read each 512 byte block into an array of bytes
// check if it is start of jpeg, if not write into previous jpeg
long totalblocks = (totalbyte/512);
long count = 1; //counter for jpeg file no. and space for counter name
char *jpegname = malloc(50);
if (jpegname == NULL)
{
printf("memory not allocated\n");
return 1;
}
//create memory for current block
uint8_t *cblock = malloc(sizeof(uint8_t) *512);
if (cblock == NULL)
{
printf("memory not allocated\n");
return 1;
}
for (int i = 0; i < totalblocks; i++)
{
FILE *output;
//read each block into cblock
fread(cblock, sizeof(uint8_t), 512, input);
if (cblock[0] == 0xff && cblock[1] == 0xd8 && cblock[2]== 0xff
&& cblock[3] >= 0xe0 && cblock[3] <= 0xef )
{//if start of jpeg found
if (count ==1) //if first file
{
sprintf(jpegname, "%03li.jpeg",count);
//open output file
output = fopen(jpegname , "w");
fwrite(cblock, sizeof(uint8_t), 512, output);
count++;
}
if (count >1)
{
// close previous file
fclose(output);
sprintf(jpegname, "%03li.jpeg",count);
output = fopen(jpegname, "w");
fwrite(cblock, sizeof(uint8_t),512,output);
count++;
}
}
//if first jpeg not found yet do nothing
if (count > 1) //if first jpeg found
{
fwrite(cblock, sizeof(uint8_t), 512, output); //keep writing to 1st jpeg
}
}
free(jpegname);
free(cblock);
return 0;
}