0

I have started working on PSET 4 RECOVERY. My program compiles successfully, it goes through the first 3 tests no problem, but for the love of me I cannot seem to find the problem.
It just does not correctly restore the photos, I have tried changing ptr to char and vice versa to no avail.

Here is the code:

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

typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
    //check for number of arguments
    if (argc != 2)
    {
        printf("Usage: ./recover filename\n");
        return 1;
    }
    //initialize files
    char *input_name = argv[1];
    FILE *input = fopen(input_name, "r");
    if (input == NULL)
    {
        //check if file is openable
        printf("File %s could not be opened!", input_name);
        return 1;
    }
    //initialize files and pointers
    BYTE file[512];
    int counter = 0;
    FILE *img = NULL;
    char img_name[8];
    //loop as long as files returns bytes
    while(fread(&file, 512, 1, input) == 1)
    {
        //check if file is jpeg
        if (file[0] == 0xff && file[1] == 0xd8 && file[2] == 0xff && (file[3] & 0xf0) == 0xe0)
        {
            //if a previous file is open, close it
            if (counter != 0)
            fclose(img);
        }
        //initialize new file
        sprintf(img_name, "%03i.jpg", counter);
        img = fopen(img_name, "w");
        counter++;
        //if jpeg is found, write
        if (counter != 0)
        {
            fwrite(&file, 512, 1, img);
        }
    }
        fclose(input);
        fclose(img);
        return 0;

Any help with the debugging is appreciated.

0

Let's look very closely at this code:

while(fread(&file, 512, 1, input) == 1)
{
    //check if file is jpeg
    if (file[0] == 0xff && file[1] == 0xd8 && file[2] == 0xff && (file[3] & 0xf0) == 0xe0)
    {
        //if a previous file is open, close it
        if (counter != 0)
        fclose(img);
    }
    //initialize new file
    sprintf(img_name, "%03i.jpg", counter);
    img = fopen(img_name, "w");
    counter++;
    //if jpeg is found, write
    if (counter != 0)
    {
        fwrite(&file, 512, 1, img);
    }
}

This code will check for a signature and, if found, will close the img file. That's all the test will handle.

The code that follows will execute for EVERY data block that follows. That means hundreds of files will be opened and have one block written to them. It could also lead to other unpredictable behavior.

Perhaps you should consider the placement of that closing curly brace for the first if statement in the code block above? What code needs to ONLY run when a signature is found and what code needs to execute on every pass of the while loop?

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

You must log in to answer this question.

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