1

I'm having trouble reading and writing the contents of the JPG files in Pset4 recover.

When I run my program, I'm getting all 50 JPGs as files 000.jpg to 049.jpg. However, the pictures all appear to be checkered black and white boards of the same thing, though of various height and width. I'm trying to pinpoint whether my code is logically incorrect or whether there is just bug somewhere in my program.

I watched Zamyla's walkthrough and I know Zamyla divided the pseudocode into If at Start of a JPG, then do the following and If Already Found a JPG, then do the following. I'm confused on why I need the second clause of If Already Found a JPG. To me, fread reads 512 bytes at a time and we know the each JPG size is 512 and all JPGs are next to each other. Therefore, I believe my code is doing the following:

  1. while we are not at end of input file
  2. reads 512 bytes into buffer
  3. reads 512 bytes until finds matches first 4 bytes of JPG
  4. once jpg is found, sprints the title
  5. opens an img FILE* img = fopen
  6. if img is not null, fwrites what is in buffer into the img
  7. closes the img and add 1 to JPG count number
  8. steps 3 - 7 are all within one if condition. Once the condition is finished for the first JPG is over, the code goes back to the fread, which will read the next 512 bytes and do the same thing.

I understand that Zamyla's pseudocode may be more efficient (b/c you are not reading the entire first 4 bytes over and over again), but is it really necessary? If so, why? If not, this tells me that there's a bug somewhere within my if condition (steps 3 - 7)...

Thank you for your help!

3

Having your psuedo-code listed by numbers are somewhat confusing. Here is what I believe you intend to do with your code. Please let me know I misunderstand.

file count = 0
WHILE not end of the file
    buffer = 512 bytes read from stream
    IF match jpg header
        open (formatted filecount).jpg
        IF file is opened
            write buffer to file
        ENDIF
        close the file
        file count++
    ENDIF
ENDWHILE

By your code's logic, it will open the new file once the header matches, write to the file then close instantly. However, JPG files are not just 512 KB in size. 512 KB is size of file blocks. Therefore, your code will ignore all other parts of JPG files except first 512 KB of each.

How about you always write 512 KB to currently opened file, if any? Header matching should only work as new file opener. This way, no data should be lost.

Good luck with your code!

| improve this answer | |
  • Ah i see what you mean. My mistake was assuming each jpg is 512 bytes. therefore, after the first 512, the next 512 is another JPG. However, that next 512 may still be part of the first JPG – jwang1191 Mar 29 '16 at 21:18

You must log in to answer this question.

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