0

I've been rewriting that code for about a week now and start beeing very confused about what I am doing wrong, I hope my logic isn't fully wrong but I have some doubts about my understanding of pointers/file_pointers and feel like that might be where my mistakes are coming from. Could you please reassure me that I'm not totally out off track and point me in the right direction so I can work on my mistakes please .

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define Block 512
typedef uint8_t BYTE;

 // Usage and File pointer check
 
int main(int argc, char *argv[])
{                                             
    if(argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }


    FILE* file = fopen(argv[1], "r");
    if(file == NULL)
    {
         printf("Could not open: %s\n", argv[1]);
    }

 //Create a buffer to store read bytes, keep track how many bytes read, how many jpeg found, create a pointer to a File called filename
 
    BYTE buffer[Block];
    int BYTES_read = fread(buffer, sizeof(BYTE), Block, file);
    int jpeg_count = 0;
    
    char* filename = NULL;
    FILE* img = fopen(filename, "w");
//Read memory card BYTES into buffer
    while(BYTES_read != 0)
    {
       
//Read 512 bytes into a buffer

        fread(buffer, sizeof(BYTE), Block, file);

  //If beginning of a jpeg 

        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {

     //if first jpeg Open a new file to write   Else close previous file before 

            if(jpeg_count > 0)
            {
                fclose(img);
            }
            sprintf(filename, "%03i.jpeg", jpeg_count);
            fwrite(buffer, sizeof(BYTE), BYTES_read, img);
            jpeg_count++;
        }
        
   //else   If no jpeg found yet Quit    Else keep writing into previous jpeg

        else
        {
            if(jpeg_count == 0)
            {
                break;
            }
            else
            {
                fwrite(buffer, sizeof(BYTE), BYTES_read, img);
            }
        }
        
    // Close all files
    
        fclose(img);
        fclose(file);
    }
}
0

The start of card.raw may not be a jpeg header. In which case your program goes straight to

    else
    {
        if(jpeg_count == 0)
        {
            break;
        } 

and calls it a day. Also, your while loop is on the condition

while(BYTES_read != 0)

but BYTES_read is initialised once prior to the while loop, and not updated within the loop. So the while loop would otherwise run forever, if it didn't break out first.

You must log in to answer this question.

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