0

My program creates 51 empty(grey) jpg files. Is problem in fwrite? Can't cope with it. Thanks for help!

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

typedef uint8_t BYTE;

int main(void)
{

    BYTE buffer[512];
    int k = 0; //counter
    char filename [8];
    FILE* jpg = NULL;

    FILE* card = fopen("card.raw", "r"); // open card file
    if (card == NULL)
    {
        printf("Could not open card");
        return 1;
    }


    while (fread(buffer, 512, 1, card) == 1) //iterate over the card file
    {

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

            if (jpg == NULL) // if jpg was found and jpg file does not exist
            {
                sprintf (filename, "%03i.jpg", k);

                jpg = fopen (filename, "a");

                fwrite (buffer, 512, 1, jpg);
            }
            if (jpg != NULL) //if jpg was found and jpg file has already exist
            {
                fclose (jpg); //close old file
                k++;
                sprintf (filename, "%03i.jpg", k);

                jpg = fopen (filename, "a"); //open new

                fwrite (buffer, 512, 1, jpg);
            }
        }

        else if (jpg != NULL)
        {
            fwrite (buffer, 512, 1, jpg);
        }

    }

    fclose (card);
}
1

The 51 files is due to the logic surrounding the creation of the first output file. On finding the first signature, the code opens the first file and writes the first 512 byte block to that file. BUT, the very next if statement checks to see if there's an open output file, so it sees that there is, immediately closes the first file, and opens the second one, writing the same block of image data to that new file. From that point on, things proceed normally, except that file 0 is in file 1, file 1 is in file 2, etc., until file 49 is in 50.

As for all the files being grey, I'm not sure, but I have an idea. Since the code is opening the output files in append mode, "a", instead of write mode, "w", so the code is appending to existing files. If you didn't delete the output files between runs, and had bad files from earlier versions of your code, they may be just bad files. You might try changing to "w" and deleting all the existing output files.

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

1
  • Thanks! I fixed the first one problem with files amount and it solved the second one too! It works :)
    – Ivanka D.
    Jun 21 '17 at 7:59

You must log in to answer this question.

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