1

Here is my code for recover.c. It compiles and runs fine, but can only retrieve three out of the sixteen images. I'm not quite sure why it does this.

// Sorry about the formatting of the top part!


int main(int argc, char* argv[]) { // open file FILE* inptr = fopen("card.raw", "r"); if (inptr == NULL) { printf("Could not open %s.\n", "card.raw"); return 2; }

// variables
int count = 0;
int block = 512;
unsigned char buffer[block];
FILE* outptr = 0; 
char name[8];

// reads blocks
while (fread(&buffer, sizeof(char), block, inptr) != 0)
{
   fread(&buffer, sizeof(char), block, inptr);

   // searches for jpegs
   if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0x30 || buffer[3] == 0xe1)) 
   {
       if (count == 0)
       {             
           sprintf(name, "%03d.jpg", count);
           outptr = fopen(name, "a");
           count++;

       }
       else
       {
           fclose(outptr);
           char title[8];
           count++;
           sprintf(title, "%03d.jpg", count);
           outptr = fopen(title, "a");

       }   
   }       
   if (count > 0)
   {
       fwrite(&buffer, sizeof(buffer), 1, outptr);
   }
}    
fclose(inptr);    
return 0;

}

Thank you!

2

You have made a very common mistake. Look at the following:

while (fread(&buffer, sizeof(char), block, inptr) != 0)
{
   fread(&buffer, sizeof(char), block, inptr);

You execute an fread() call in the while statement, then immediately execute another fread() call, thus throwing away the data from the previous read without processing it. In other words, you're only processing half of the data. I'm surprised that you got three files created. Usually, this results in 0 files created.

The fread() in the while statement isn't simply a test condition, it is an actual execution of the read. The returned result from that read is what you are testing.

There may be other issues, but this is the main problem here.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

4
  • Thank you for pointing that out! I removed it. However, my code still only retrieves three images. Any other ideas? Dec 24 '15 at 0:17
  • Yes. Do you see anything wrong with if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0x30 || buffer[3] == 0xe1)) ?
    – Cliff B
    Dec 24 '15 at 0:39
  • You have other issues with your code, including opening files for append instead of write, but you should be able to figure them out quickly.
    – Cliff B
    Dec 24 '15 at 0:59
  • I have it working now, thank you so much! Dec 24 '15 at 1:05

You must log in to answer this question.

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