I am currently working on cs50's pset4 recover. I have managed to compile the program. However, when run, the images are corrupt and apparently, according to image viewer, are not jpeg files, because they start with different code. My program follows below. Any help would be great. Thanks!

[MOD: hid code behind edit link per academic honesty policy]


Your code has 3 mistakes that prevent it from working.

  1. It's probably just a typo but it's the problem that causes the most damage. Right above the inner while loop you have:

    fwrite(&buffer, sizeof(buffer), 1, file);

    But you shouldn't write on the file, but on the img.

  2. Next is the inner while loop. Let's follow your code from the line below and see what happens. You read in the buffer, your while loop checks for the start of a jpg, doesn't find one, as it was checked by the previous if, writes the contents of the buffer, refills it, checks. Let's assume that this finds all images and arrives at the last one. How does it know where to stop? It will cause an infinite loop that will keep reading from the file, never finding anything new as you don't check for feof down there while reading. You will have to fix that yourself.

  3. Next is the condition of the inner while loop itself. According to De Morgan's Law the opposite of

    buffer[0]==0xff && buffer[1]==0xd8 && buffer[2]==0xff && (buffer[3]==0xe0 || buffer[3]==0xe1)

    is not

    buffer[0]!=0xff && buffer[1]!=0xd8 && buffer[2]!=0xff && (buffer[3]!=0xe0 || buffer[3]!=0xe1)

    that you have in your condition, but

    buffer[0]!=0xff || buffer[1]!=0xd8 || buffer[2]!=0xff || (buffer[3]!=0xe0 && buffer[3]!=0xe1)

    Check the link above or do some more searching on your own on De Morgan to understand it.

If you fix those I think your program will be complete.

If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark.

  • 1
    Thanks! Great Help! – AWATHIEU Aug 12 '15 at 14:58
  1. using feof with a loop can be tricky, you might want to use a forever loop:

    while (1)

  2. try this declaration for buffer:

    BYTE buffer[512] = {}

within the while loop, then just read the file byte by byte into this, until you've read 512 bytes. Fwrite this to your img output file. Keep on doing this and stop when you reach feof, or when you reach a block whose first 4 bytes denote the start of a new jpg file. You should then close the current file you're writing to, if any, and name it. Your sequence above is out of order.

You must log in to answer this question.

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