I'm a bit stuck with my code. I guess the logic is correct, but the program doesn't give me any output and I have to kill it. Debug is showing me, that the problem is somewhere in checking, if the buffer is JPG's or not. Probably I've described the functions badly in the end?
Many thanks for any hint!
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isJpg(int *buffer);
bool isEof(int *buffer);
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover file\n");
return 1;
}
// remember filename
char *file = argv[1];
// open and check input file
FILE *inptr = fopen(file, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", file);
return 2;
}
// declare the 512b chunk of memory
int buffer[512];
// declare the counter
int counter = -1;
// declare variable for the filenames
char photo[3];
// read infile until found a 1st JPEG
do
{
fread(&buffer, 512, 1, inptr);
}
while (!isJpg(buffer));
// read infile's all 512b chunks until EoF
do
{
// start the counter and increase it
counter++;
// create the outfile with a correct name
sprintf(photo, "%03i.jpg", counter);
FILE *outptr = fopen(photo, "w");
// write the 1st chunk to outfile
fwrite(&buffer, 512, 1, outptr);
// write the chunks until we reach next jpg
while (!isJpg(buffer))
{
fread(&buffer, 1, 512, inptr);
fwrite(&buffer, 512, 1, outptr);
}
// when next jpg is reached, clouse the outfile
fclose(outptr);
if (isEof(buffer))
{
// if EoF reached, close the infile
fclose(inptr);
// if any outfile exists, write the remaining chunk and close it
if (outptr != NULL)
{
fwrite(&buffer, sizeof(buffer), 1, outptr);
fclose(outptr);
}
}
}
while (!isJpg(buffer));
}
// this function checks for first 4 bytes
bool isJpg (int *buffer)
{
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
return true;
}
else return false;
}
// this function checks, if the end of file is here
bool isEof (int *buffer)
{
if (sizeof(buffer) < 512) return true;
else return false;
}