0

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);

}

2

You're reading your buffer 2 times per iteration, I'm not sure how do while loops exactly work in C (I think they run in order, but you should check that), but I think your main problem is that first fread statement at the start of the loop, you're already reading it in the while check statement. You might need to put it outside or simply remove it, I'm not sure. I think it does help to think fread in terms of a "phonograph", like every time you call it, it's like you spin the handle forward, and the record goes from that point the next time you spin it.

  • Thank you so much! It was the problem with two fread statement .. just unbelievable how easy the solution was. Thanks a lot! – Dawienchi Apr 2 '19 at 14:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .