0

I need your help with pset4 recover, as image does not recover correctly. And I would like to have more understanding on how file pointer works. Below is what I have written which generate no correct image recovered. Your assistance would be very much appreciated.

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

 typedef uint8_t BYTE;


 int main(int argc, char *argv[])
 {
//check if under included 2 arguement 
if (argc != 2)
{
    return 1;
}

//open the original file
FILE *inptr = fopen(argv[1], "r");
{
    if (inptr == NULL)
    {
        fclose(inptr);
        return 1;
    }
}

//make temporary storage for 512 bytes
BYTE buffer[512];

int jpg_count = 0;
//keep reading until end of the file
do
{
    fread(buffer, sizeof(BYTE), 512, inptr); //(data to, size, how many, data from)

    //check if it is jpg
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        //name the jpg file
        char filename[7];
        sprintf(filename, "%03i.jpg", jpg_count);


        //write the first block in a jpg file
        FILE* outptr = fopen(filename, "w");

        if (outptr == NULL)
        {
            fclose(inptr);
            fclose(outptr);
            return 1;
        }

        fwrite(buffer, sizeof(BYTE), 512, outptr); //(data from, size, how many, data to)

        //read next
        fread(buffer, sizeof(BYTE), 512, inptr); 

        //write while it is not encounter a new jpg file
        while ((buffer[0] != 0xff || buffer[1] != 0xd8 || buffer[2] != 0xff || (buffer[3] & 0xf0) != 0xe0) && fread(buffer, sizeof(BYTE), 512, inptr) == 512)
        {
            fwrite(buffer, sizeof(BYTE), 512, outptr); 
            fread(buffer, sizeof(BYTE), 512, inptr);
        }
        fclose(outptr);
        jpg_count ++;

        fseek(inptr, sizeof(BYTE) * 512, SEEK_CUR);
    }

}
while (fread(buffer, sizeof(BYTE), 512, inptr) == 512);

fclose(inptr);
}
0

When you created the string var to hold the 7 char filename, did you think to leave another space for the end of string marker????

  • Thank you. I figure it out after finding several errors including what you kindly advised me on. – Pedarun Apr 18 '20 at 12:58

You must log in to answer this question.

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