0

My code works for the card.raw that is given part of the problem set. However, it times out when I use check50. Does anyone know why even though the code compiles rather quickly for the card.raw? Or is there any optimisation I can do to my code

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Check for one command line argument
    if (argc != 2)
    {
        return 1;
    }
    // Open file given by user for read
    FILE *recover_file = fopen(argv[1], "r");
    // Check if file exists
    if (recover_file == NULL)
    {
        return 1;
    }
    // Allocate 512 bytes of memory to pointer block
    BYTE block[512];
    // Initialise variables for creation of filenames
    char filename[8];
    int filenum = 0;
    // Read file until first JPEG image appears
    while (block[0] != 0xff || block[1] != 0xd8 || block[2] != 0xff || (block[3] & 0xf0) != 0xe0)
    {
        fread(block, 1, 512, recover_file);
    }
    while (!feof(recover_file))
    {
        sprintf(filename, "%03i.jpg", filenum);
        FILE *outfile = fopen(filename, "w");
        fwrite(block, 1, 512, outfile);
        fread(block, 1, 512, recover_file);
        while (block[0] != 0xff || block[1] != 0xd8 || block[2] != 0xff || (block[3] & 0xf0) != 0xe0)
        {
            fwrite(block, 1, 512, outfile);
            fread(block, 1, 512, recover_file);
        }
        fclose(outfile);
        filenum++;
    }
    fclose(recover_file);
}
0

Before the first while loop you never initialize block by filling it up with fread, so the while loop won't do it's job. Also when calling fread() it's good to check the return value, in this case the number of bytes copied to your variable.

You must log in to answer this question.

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