0

I'm having problem with my pset 4 recover assignment,

my code can compile and produce 49 jpg documents with the right name, but check50 told me they don't match with the right jpgs.

Is there anything wrong with my logic? Thanks in advance!

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

typedef uint8_t BYTE;
int BLOCK_SIZE = 512;

int main(int argc, char *argv[])
{
    // Ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    // Open input file
    FILE *infile = fopen(argv[1], "r");
    if (infile == NULL)
    {
        printf("Could not open %s.\n", argv[1]);
        return 2;
    }
    //allocate memory for file name and for buffer
    char *filename = malloc(8 * sizeof(char));
    BYTE *buffer = malloc(BLOCK_SIZE * sizeof(BYTE));
    int k = 0;
    FILE *outfile;

    while (fread(buffer, sizeof(BYTE), BLOCK_SIZE, infile) == BLOCK_SIZE)
    {
        //find the signature
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
        {
            //close the outfile already opened(if there is one)
            if (k > 0)
            {
                fclose(outfile);
            }
            //create new file and start writing
            k = k + 1;
            sprintf(filename, "%03i.jpg", k-1);
            outfile = fopen(filename,"w");

            if (outfile == NULL)
            {
                printf("Could not open %s.\n", filename);
            }

            fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
        }
        //if this block has no signature, directly write
        else
        {
            if (k > 0)
            {
                fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
            }
        }
    }

    //finishe writing the last picture
    if (k > 0)
    {
        fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
    }
    // Close outfile
    fclose(outfile);
    fclose(infile);
    free(filename);
    free(buffer);
    return 0;
}

1 Answer 1

0

buffer is declared a pointer here BYTE *buffer = malloc(BLOCK_SIZE * sizeof(BYTE));. &buffer is the address assigned to the pointer. The fwrites should write the contents of the variable(buffer) not the address of the variable (&buffer)

1
  • thanks for saving me!
    – Eva Chen
    Commented Dec 29, 2022 at 12:07

You must log in to answer this question.

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