I am fighting with the recover challenge in pset4. Had some progress and was able to detect 20 images. But then my condition for finding EOF is true and the program stops.
I think the problem is, that my program doesn't correclty recognize the beginning of a new jpg, after it finds the first one. But I cant figure out, where the bug is.
Hopefully guys, you can help me! :)
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
int main(int argc, char *argv[])
{
//Checks if argc = 1
if (argc !=2)
{
printf("Please only enter filename\n");
return 1;
}
//Assigning files
char *infile = argv[1];
//Creats and Checks if input & output file can be open
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open file\n");
return 2;
}
unsigned char buffer[512];
bool fileopen = false;
int counter = -1;
char filename[8];
FILE *img = fopen("test", "w");
do
{
fread(buffer, 1, 512, inptr);
if ((buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) && fileopen == true)
{
fclose(img);
counter++;
sprintf(filename, "%03i.jpg", counter);
img = fopen(filename, "w");
fileopen = true;
}
else if ((buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) && fileopen == false)
{
fclose(img);
counter++;
sprintf(filename, "%03i.jpg", counter);
img = fopen(filename, "w");
fileopen = true;
}
if (fileopen == true)
{
fwrite(buffer, 1, 512, img);
}
}
while(fread(buffer, 1, 512, inptr)==512);
fclose(img);
fclose(inptr);
}